BaseStringHelper.php 18 KB

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