StringHelper.php 18 KB

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