BaseStringHelper.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\helpers;
  8. use Yii;
  9. /**
  10. * BaseStringHelper provides concrete implementation for [[StringHelper]].
  11. *
  12. * Do not use BaseStringHelper. Use [[StringHelper]] instead.
  13. *
  14. * @author Qiang Xue <qiang.xue@gmail.com>
  15. * @author Alex Makarov <sam@rmcreative.ru>
  16. * @since 2.0
  17. */
  18. class BaseStringHelper
  19. {
  20. /**
  21. * Returns the number of bytes in the given string.
  22. * This method ensures the string is treated as a byte array by using `mb_strlen()`.
  23. *
  24. * @param string $string the string being measured for length
  25. * @return int the number of bytes in the given string.
  26. */
  27. public static function byteLength($string)
  28. {
  29. return mb_strlen((string)$string, '8bit');
  30. }
  31. /**
  32. * Returns the portion of string specified by the start and length parameters.
  33. * This method ensures the string is treated as a byte array by using `mb_substr()`.
  34. *
  35. * @param string $string the input string. Must be one character or longer.
  36. * @param int $start the starting position
  37. * @param int $length the desired portion length. If not specified or `null`, there will be
  38. * no limit on length i.e. the output will be until the end of the string.
  39. * @return string the extracted part of string, or FALSE on failure or an empty string.
  40. * @see https://www.php.net/manual/en/function.substr.php
  41. */
  42. public static function byteSubstr($string, $start, $length = null)
  43. {
  44. if ($length === null) {
  45. $length = static::byteLength($string);
  46. }
  47. return mb_substr($string, $start, $length, '8bit');
  48. }
  49. /**
  50. * Returns the trailing name component of a path.
  51. * This method is similar to the php function `basename()` except that it will
  52. * treat both \ and / as directory separators, independent of the operating system.
  53. * This method was mainly created to work on php namespaces. When working with real
  54. * file paths, php's `basename()` should work fine for you.
  55. * Note: this method is not aware of the actual filesystem, or path components such as "..".
  56. *
  57. * @param string $path A path string.
  58. * @param string $suffix If the name component ends in suffix this will also be cut off.
  59. * @return string the trailing name component of the given path.
  60. * @see https://www.php.net/manual/en/function.basename.php
  61. */
  62. public static function basename($path, $suffix = '')
  63. {
  64. $len = mb_strlen($suffix);
  65. if ($len > 0 && mb_substr($path, -$len) === $suffix) {
  66. $path = mb_substr($path, 0, -$len);
  67. }
  68. $path = rtrim(str_replace('\\', '/', $path), '/');
  69. $pos = mb_strrpos($path, '/');
  70. if ($pos !== false) {
  71. return mb_substr($path, $pos + 1);
  72. }
  73. return $path;
  74. }
  75. /**
  76. * Returns parent directory's path.
  77. * This method is similar to `dirname()` except that it will treat
  78. * both \ and / as directory separators, independent of the operating system.
  79. *
  80. * @param string $path A path string.
  81. * @return string the parent directory's path.
  82. * @see https://www.php.net/manual/en/function.basename.php
  83. */
  84. public static function dirname($path)
  85. {
  86. $normalizedPath = rtrim(
  87. str_replace('\\', '/', $path),
  88. '/'
  89. );
  90. $separatorPosition = mb_strrpos($normalizedPath, '/');
  91. if ($separatorPosition !== false) {
  92. return mb_substr($path, 0, $separatorPosition);
  93. }
  94. return '';
  95. }
  96. /**
  97. * Truncates a string to the number of characters specified.
  98. *
  99. * @param string $string The string to truncate.
  100. * @param int $length How many characters from original string to include into truncated string.
  101. * @param string $suffix String to append to the end of truncated string.
  102. * @param string $encoding The charset to use, defaults to charset currently used by application.
  103. * @param bool $asHtml Whether to treat the string being truncated as HTML and preserve proper HTML tags.
  104. * This parameter is available since version 2.0.1.
  105. * @return string the truncated string.
  106. */
  107. public static function truncate($string, $length, $suffix = '...', $encoding = null, $asHtml = false)
  108. {
  109. if ($encoding === null) {
  110. $encoding = Yii::$app ? Yii::$app->charset : 'UTF-8';
  111. }
  112. if ($asHtml) {
  113. return static::truncateHtml($string, $length, $suffix, $encoding);
  114. }
  115. if (mb_strlen($string, $encoding) > $length) {
  116. return rtrim(mb_substr($string, 0, $length, $encoding)) . $suffix;
  117. }
  118. return $string;
  119. }
  120. /**
  121. * Truncates a string to the number of words specified.
  122. *
  123. * @param string $string The string to truncate.
  124. * @param int $count How many words from original string to include into truncated string.
  125. * @param string $suffix String to append to the end of truncated string.
  126. * @param bool $asHtml Whether to treat the string being truncated as HTML and preserve proper HTML tags.
  127. * This parameter is available since version 2.0.1.
  128. * @return string the truncated string.
  129. */
  130. public static function truncateWords($string, $count, $suffix = '...', $asHtml = false)
  131. {
  132. if ($asHtml) {
  133. return static::truncateHtml($string, $count, $suffix);
  134. }
  135. $words = preg_split('/(\s+)/u', trim($string), 0, PREG_SPLIT_DELIM_CAPTURE);
  136. if (count($words) / 2 > $count) {
  137. return implode('', array_slice($words, 0, ($count * 2) - 1)) . $suffix;
  138. }
  139. return $string;
  140. }
  141. /**
  142. * Truncate a string while preserving the HTML.
  143. *
  144. * @param string $string The string to truncate
  145. * @param int $count The counter
  146. * @param string $suffix String to append to the end of the truncated string.
  147. * @param string|bool $encoding Encoding flag or charset.
  148. * @return string
  149. * @since 2.0.1
  150. */
  151. protected static function truncateHtml($string, $count, $suffix, $encoding = false)
  152. {
  153. $config = \HTMLPurifier_Config::create(null);
  154. if (Yii::$app !== null) {
  155. $config->set('Cache.SerializerPath', Yii::$app->getRuntimePath());
  156. }
  157. $lexer = \HTMLPurifier_Lexer::create($config);
  158. $tokens = $lexer->tokenizeHTML($string, $config, new \HTMLPurifier_Context());
  159. $openTokens = [];
  160. $totalCount = 0;
  161. $depth = 0;
  162. $truncated = [];
  163. foreach ($tokens as $token) {
  164. if ($token instanceof \HTMLPurifier_Token_Start) { //Tag begins
  165. $openTokens[$depth] = $token->name;
  166. $truncated[] = $token;
  167. ++$depth;
  168. } elseif ($token instanceof \HTMLPurifier_Token_Text && $totalCount <= $count) { //Text
  169. if (false === $encoding) {
  170. preg_match('/^(\s*)/um', $token->data, $prefixSpace) ?: $prefixSpace = ['', ''];
  171. $token->data = $prefixSpace[1] . self::truncateWords(ltrim($token->data), $count - $totalCount, '');
  172. $currentCount = self::countWords($token->data);
  173. } else {
  174. $token->data = self::truncate($token->data, $count - $totalCount, '', $encoding);
  175. $currentCount = mb_strlen($token->data, $encoding);
  176. }
  177. $totalCount += $currentCount;
  178. $truncated[] = $token;
  179. } elseif ($token instanceof \HTMLPurifier_Token_End) { //Tag ends
  180. if ($token->name === $openTokens[$depth - 1]) {
  181. --$depth;
  182. unset($openTokens[$depth]);
  183. $truncated[] = $token;
  184. }
  185. } elseif ($token instanceof \HTMLPurifier_Token_Empty) { //Self contained tags, i.e. <img/> etc.
  186. $truncated[] = $token;
  187. }
  188. if ($totalCount >= $count) {
  189. if (0 < count($openTokens)) {
  190. krsort($openTokens);
  191. foreach ($openTokens as $name) {
  192. $truncated[] = new \HTMLPurifier_Token_End($name);
  193. }
  194. }
  195. break;
  196. }
  197. }
  198. $context = new \HTMLPurifier_Context();
  199. $generator = new \HTMLPurifier_Generator($config, $context);
  200. return $generator->generateFromTokens($truncated) . ($totalCount >= $count ? $suffix : '');
  201. }
  202. /**
  203. * Check if given string starts with specified substring. Binary and multibyte safe.
  204. *
  205. * @param string $string Input string
  206. * @param string $with Part to search inside the $string
  207. * @param bool $caseSensitive Case sensitive search. Default is true. When case sensitive is enabled, `$with` must
  208. * exactly match the starting of the string in order to get a true value.
  209. * @return bool Returns true if first input starts with second input, false otherwise
  210. */
  211. public static function startsWith($string, $with, $caseSensitive = true)
  212. {
  213. if (!$bytes = static::byteLength($with)) {
  214. return true;
  215. }
  216. if ($caseSensitive) {
  217. return strncmp($string, $with, $bytes) === 0;
  218. }
  219. $encoding = Yii::$app ? Yii::$app->charset : 'UTF-8';
  220. $string = static::byteSubstr($string, 0, $bytes);
  221. return mb_strtolower($string, $encoding) === mb_strtolower($with, $encoding);
  222. }
  223. /**
  224. * Check if given string ends with specified substring. Binary and multibyte safe.
  225. *
  226. * @param string $string Input string to check
  227. * @param string $with Part to search inside of the `$string`.
  228. * @param bool $caseSensitive Case sensitive search. Default is true. When case sensitive is enabled, `$with` must
  229. * exactly match the ending of the string in order to get a true value.
  230. * @return bool Returns true if first input ends with second input, false otherwise
  231. */
  232. public static function endsWith($string, $with, $caseSensitive = true)
  233. {
  234. if (!$bytes = static::byteLength($with)) {
  235. return true;
  236. }
  237. if ($caseSensitive) {
  238. // Warning check, see https://php.net/substr-compare#refsect1-function.substr-compare-returnvalues
  239. if (static::byteLength($string) < $bytes) {
  240. return false;
  241. }
  242. return substr_compare($string, $with, -$bytes, $bytes) === 0;
  243. }
  244. $encoding = Yii::$app ? Yii::$app->charset : 'UTF-8';
  245. $string = static::byteSubstr($string, -$bytes);
  246. return mb_strtolower($string, $encoding) === mb_strtolower($with, $encoding);
  247. }
  248. /**
  249. * Explodes string into array, optionally trims values and skips empty ones.
  250. *
  251. * @param string $string String to be exploded.
  252. * @param string $delimiter Delimiter. Default is ','.
  253. * @param mixed $trim Whether to trim each element. Can be:
  254. * - boolean - to trim normally;
  255. * - string - custom characters to trim. Will be passed as a second argument to `trim()` function.
  256. * - callable - will be called for each value instead of trim. Takes the only argument - value.
  257. * @param bool $skipEmpty Whether to skip empty strings between delimiters. Default is false.
  258. * @return array
  259. * @since 2.0.4
  260. */
  261. public static function explode($string, $delimiter = ',', $trim = true, $skipEmpty = false)
  262. {
  263. $result = explode($delimiter, $string);
  264. if ($trim !== false) {
  265. if ($trim === true) {
  266. $trim = 'trim';
  267. } elseif (!is_callable($trim)) {
  268. $trim = function ($v) use ($trim) {
  269. return trim($v, $trim);
  270. };
  271. }
  272. $result = array_map($trim, $result);
  273. }
  274. if ($skipEmpty) {
  275. // Wrapped with array_values to make array keys sequential after empty values removing
  276. $result = array_values(array_filter($result, function ($value) {
  277. return $value !== '';
  278. }));
  279. }
  280. return $result;
  281. }
  282. /**
  283. * Counts words in a string.
  284. *
  285. * @param string $string the text to calculate
  286. * @return int
  287. * @since 2.0.8
  288. */
  289. public static function countWords($string)
  290. {
  291. return count(preg_split('/\s+/u', $string, 0, PREG_SPLIT_NO_EMPTY));
  292. }
  293. /**
  294. * Returns string representation of number value with replaced commas to dots, if decimal point
  295. * of current locale is comma.
  296. *
  297. * @param int|float|string $value the value to normalize.
  298. * @return string
  299. * @since 2.0.11
  300. */
  301. public static function normalizeNumber($value)
  302. {
  303. $value = (string) $value;
  304. $localeInfo = localeconv();
  305. $decimalSeparator = isset($localeInfo['decimal_point']) ? $localeInfo['decimal_point'] : null;
  306. if ($decimalSeparator !== null && $decimalSeparator !== '.') {
  307. $value = str_replace($decimalSeparator, '.', $value);
  308. }
  309. return $value;
  310. }
  311. /**
  312. * Encodes string into "Base 64 Encoding with URL and Filename Safe Alphabet" (RFC 4648).
  313. *
  314. * > Note: Base 64 padding `=` may be at the end of the returned string.
  315. * > `=` is not transparent to URL encoding.
  316. *
  317. * @param string $input the string to encode.
  318. * @return string encoded string.
  319. * @see https://tools.ietf.org/html/rfc4648#page-7
  320. * @since 2.0.12
  321. */
  322. public static function base64UrlEncode($input)
  323. {
  324. return strtr(base64_encode($input), '+/', '-_');
  325. }
  326. /**
  327. * Decodes "Base 64 Encoding with URL and Filename Safe Alphabet" (RFC 4648).
  328. *
  329. * @param string $input encoded string.
  330. * @return string decoded string.
  331. * @see https://tools.ietf.org/html/rfc4648#page-7
  332. * @since 2.0.12
  333. */
  334. public static function base64UrlDecode($input)
  335. {
  336. return base64_decode(strtr($input, '-_', '+/'));
  337. }
  338. /**
  339. * Safely casts a float to string independent of the current locale.
  340. * The decimal separator will always be `.`.
  341. *
  342. * @param float|int $number a floating point number or integer.
  343. * @return string the string representation of the number.
  344. * @since 2.0.13
  345. */
  346. public static function floatToString($number)
  347. {
  348. // . and , are the only decimal separators known in ICU data,
  349. // so its safe to call str_replace here
  350. return str_replace(',', '.', (string) $number);
  351. }
  352. /**
  353. * Checks if the passed string would match the given shell wildcard pattern.
  354. * This function emulates [[fnmatch()]], which may be unavailable at certain environment, using PCRE.
  355. *
  356. * @param string $pattern the shell wildcard pattern.
  357. * @param string $string the tested string.
  358. * @param array $options options for matching. Valid options are:
  359. *
  360. * - caseSensitive: bool, whether pattern should be case sensitive. Defaults to `true`.
  361. * - escape: bool, whether backslash escaping is enabled. Defaults to `true`.
  362. * - filePath: bool, whether slashes in string only matches slashes in the given pattern. Defaults to `false`.
  363. *
  364. * @return bool whether the string matches pattern or not.
  365. * @since 2.0.14
  366. */
  367. public static function matchWildcard($pattern, $string, $options = [])
  368. {
  369. if ($pattern === '*' && empty($options['filePath'])) {
  370. return true;
  371. }
  372. $replacements = [
  373. '\\\\\\\\' => '\\\\',
  374. '\\\\\\*' => '[*]',
  375. '\\\\\\?' => '[?]',
  376. '\*' => '.*',
  377. '\?' => '.',
  378. '\[\!' => '[^',
  379. '\[' => '[',
  380. '\]' => ']',
  381. '\-' => '-',
  382. ];
  383. if (isset($options['escape']) && !$options['escape']) {
  384. unset($replacements['\\\\\\\\']);
  385. unset($replacements['\\\\\\*']);
  386. unset($replacements['\\\\\\?']);
  387. }
  388. if (!empty($options['filePath'])) {
  389. $replacements['\*'] = '[^/\\\\]*';
  390. $replacements['\?'] = '[^/\\\\]';
  391. }
  392. $pattern = strtr(preg_quote($pattern, '#'), $replacements);
  393. $pattern = '#^' . $pattern . '$#us';
  394. if (isset($options['caseSensitive']) && !$options['caseSensitive']) {
  395. $pattern .= 'i';
  396. }
  397. return preg_match($pattern, (string)$string) === 1;
  398. }
  399. /**
  400. * This method provides a unicode-safe implementation of built-in PHP function `ucfirst()`.
  401. *
  402. * @param string $string the string to be proceeded
  403. * @param string $encoding Optional, defaults to "UTF-8"
  404. * @return string
  405. * @see https://www.php.net/manual/en/function.ucfirst.php
  406. * @since 2.0.16
  407. */
  408. public static function mb_ucfirst($string, $encoding = 'UTF-8')
  409. {
  410. $firstChar = mb_substr((string)$string, 0, 1, $encoding);
  411. $rest = mb_substr((string)$string, 1, null, $encoding);
  412. return mb_strtoupper($firstChar, $encoding) . $rest;
  413. }
  414. /**
  415. * This method provides a unicode-safe implementation of built-in PHP function `ucwords()`.
  416. *
  417. * @param string $string the string to be proceeded
  418. * @param string $encoding Optional, defaults to "UTF-8"
  419. * @return string
  420. * @see https://www.php.net/manual/en/function.ucwords
  421. * @since 2.0.16
  422. */
  423. public static function mb_ucwords($string, $encoding = 'UTF-8')
  424. {
  425. $string = (string) $string;
  426. if (empty($string)) {
  427. return $string;
  428. }
  429. $parts = preg_split('/(\s+[^\w]+\s+|^[^\w]+\s+|\s+)/u', $string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
  430. $ucfirstEven = trim(mb_substr($parts[0], -1, 1, $encoding)) === '';
  431. foreach ($parts as $key => $value) {
  432. $isEven = (bool)($key % 2);
  433. if ($ucfirstEven === $isEven) {
  434. $parts[$key] = static::mb_ucfirst($value, $encoding);
  435. }
  436. }
  437. return implode('', $parts);
  438. }
  439. }