Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

BaseStringHelper.php 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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. * @param string $string the string being measured for length
  24. * @return integer the number of bytes in the given string.
  25. */
  26. public static function byteLength($string)
  27. {
  28. return mb_strlen($string, '8bit');
  29. }
  30. /**
  31. * Returns the portion of string specified by the start and length parameters.
  32. * This method ensures the string is treated as a byte array by using `mb_substr()`.
  33. * @param string $string the input string. Must be one character or longer.
  34. * @param integer $start the starting position
  35. * @param integer $length the desired portion length. If not specified or `null`, there will be
  36. * no limit on length i.e. the output will be until the end of the string.
  37. * @return string the extracted part of string, or FALSE on failure or an empty string.
  38. * @see http://www.php.net/manual/en/function.substr.php
  39. */
  40. public static function byteSubstr($string, $start, $length = null)
  41. {
  42. return mb_substr($string, $start, $length === null ? mb_strlen($string, '8bit') : $length, '8bit');
  43. }
  44. /**
  45. * Returns the trailing name component of a path.
  46. * This method is similar to the php function `basename()` except that it will
  47. * treat both \ and / as directory separators, independent of the operating system.
  48. * This method was mainly created to work on php namespaces. When working with real
  49. * file paths, php's `basename()` should work fine for you.
  50. * Note: this method is not aware of the actual filesystem, or path components such as "..".
  51. *
  52. * @param string $path A path string.
  53. * @param string $suffix If the name component ends in suffix this will also be cut off.
  54. * @return string the trailing name component of the given path.
  55. * @see http://www.php.net/manual/en/function.basename.php
  56. */
  57. public static function basename($path, $suffix = '')
  58. {
  59. if (($len = mb_strlen($suffix)) > 0 && mb_substr($path, -$len) === $suffix) {
  60. $path = mb_substr($path, 0, -$len);
  61. }
  62. $path = rtrim(str_replace('\\', '/', $path), '/\\');
  63. if (($pos = mb_strrpos($path, '/')) !== false) {
  64. return mb_substr($path, $pos + 1);
  65. }
  66. return $path;
  67. }
  68. /**
  69. * Returns parent directory's path.
  70. * This method is similar to `dirname()` except that it will treat
  71. * both \ and / as directory separators, independent of the operating system.
  72. *
  73. * @param string $path A path string.
  74. * @return string the parent directory's path.
  75. * @see http://www.php.net/manual/en/function.basename.php
  76. */
  77. public static function dirname($path)
  78. {
  79. $pos = mb_strrpos(str_replace('\\', '/', $path), '/');
  80. if ($pos !== false) {
  81. return mb_substr($path, 0, $pos);
  82. } else {
  83. return '';
  84. }
  85. }
  86. /**
  87. * Truncates a string to the number of characters specified.
  88. *
  89. * @param string $string The string to truncate.
  90. * @param integer $length How many characters from original string to include into truncated string.
  91. * @param string $suffix String to append to the end of truncated string.
  92. * @param string $encoding The charset to use, defaults to charset currently used by application.
  93. * @param boolean $asHtml Whether to treat the string being truncated as HTML and preserve proper HTML tags.
  94. * This parameter is available since version 2.0.1.
  95. * @return string the truncated string.
  96. */
  97. public static function truncate($string, $length, $suffix = '...', $encoding = null, $asHtml = false)
  98. {
  99. if ($asHtml) {
  100. return static::truncateHtml($string, $length, $suffix, $encoding ?: Yii::$app->charset);
  101. }
  102. if (mb_strlen($string, $encoding ?: Yii::$app->charset) > $length) {
  103. return rtrim(mb_substr($string, 0, $length, $encoding ?: Yii::$app->charset)) . $suffix;
  104. } else {
  105. return $string;
  106. }
  107. }
  108. /**
  109. * Truncates a string to the number of words specified.
  110. *
  111. * @param string $string The string to truncate.
  112. * @param integer $count How many words from original string to include into truncated string.
  113. * @param string $suffix String to append to the end of truncated string.
  114. * @param boolean $asHtml Whether to treat the string being truncated as HTML and preserve proper HTML tags.
  115. * This parameter is available since version 2.0.1.
  116. * @return string the truncated string.
  117. */
  118. public static function truncateWords($string, $count, $suffix = '...', $asHtml = false)
  119. {
  120. if ($asHtml) {
  121. return static::truncateHtml($string, $count, $suffix);
  122. }
  123. $words = preg_split('/(\s+)/u', trim($string), null, PREG_SPLIT_DELIM_CAPTURE);
  124. if (count($words) / 2 > $count) {
  125. return implode('', array_slice($words, 0, ($count * 2) - 1)) . $suffix;
  126. } else {
  127. return $string;
  128. }
  129. }
  130. /**
  131. * Truncate a string while preserving the HTML.
  132. *
  133. * @param string $string The string to truncate
  134. * @param integer $count
  135. * @param string $suffix String to append to the end of the truncated string.
  136. * @param string|boolean $encoding
  137. * @return string
  138. * @since 2.0.1
  139. */
  140. protected static function truncateHtml($string, $count, $suffix, $encoding = false)
  141. {
  142. $config = \HTMLPurifier_Config::create(null);
  143. $config->set('Cache.SerializerPath', \Yii::$app->getRuntimePath());
  144. $lexer = \HTMLPurifier_Lexer::create($config);
  145. $tokens = $lexer->tokenizeHTML($string, $config, null);
  146. $openTokens = 0;
  147. $totalCount = 0;
  148. $truncated = [];
  149. foreach ($tokens as $token) {
  150. if ($token instanceof \HTMLPurifier_Token_Start) { //Tag begins
  151. $openTokens++;
  152. $truncated[] = $token;
  153. } elseif ($token instanceof \HTMLPurifier_Token_Text && $totalCount <= $count) { //Text
  154. if (false === $encoding) {
  155. preg_match('/^(\s*)/um', $token->data, $prefixSpace) ?: $prefixSpace = ['',''];
  156. $token->data = $prefixSpace[1] . self::truncateWords(ltrim($token->data), $count - $totalCount, '');
  157. $currentCount = self::countWords($token->data);
  158. } else {
  159. $token->data = self::truncate($token->data, $count - $totalCount, '', $encoding);
  160. $currentCount = mb_strlen($token->data, $encoding);
  161. }
  162. $totalCount += $currentCount;
  163. $truncated[] = $token;
  164. } elseif ($token instanceof \HTMLPurifier_Token_End) { //Tag ends
  165. $openTokens--;
  166. $truncated[] = $token;
  167. } elseif ($token instanceof \HTMLPurifier_Token_Empty) { //Self contained tags, i.e. <img/> etc.
  168. $truncated[] = $token;
  169. }
  170. if (0 === $openTokens && $totalCount >= $count) {
  171. break;
  172. }
  173. }
  174. $context = new \HTMLPurifier_Context();
  175. $generator = new \HTMLPurifier_Generator($config, $context);
  176. return $generator->generateFromTokens($truncated) . ($totalCount >= $count ? $suffix : '');
  177. }
  178. /**
  179. * Check if given string starts with specified substring.
  180. * Binary and multibyte safe.
  181. *
  182. * @param string $string Input string
  183. * @param string $with Part to search
  184. * @param boolean $caseSensitive Case sensitive search. Default is true.
  185. * @return boolean Returns true if first input starts with second input, false otherwise
  186. */
  187. public static function startsWith($string, $with, $caseSensitive = true)
  188. {
  189. if (!$bytes = static::byteLength($with)) {
  190. return true;
  191. }
  192. if ($caseSensitive) {
  193. return strncmp($string, $with, $bytes) === 0;
  194. } else {
  195. return mb_strtolower(mb_substr($string, 0, $bytes, '8bit'), Yii::$app->charset) === mb_strtolower($with, Yii::$app->charset);
  196. }
  197. }
  198. /**
  199. * Check if given string ends with specified substring.
  200. * Binary and multibyte safe.
  201. *
  202. * @param string $string
  203. * @param string $with
  204. * @param boolean $caseSensitive Case sensitive search. Default is true.
  205. * @return boolean Returns true if first input ends with second input, false otherwise
  206. */
  207. public static function endsWith($string, $with, $caseSensitive = true)
  208. {
  209. if (!$bytes = static::byteLength($with)) {
  210. return true;
  211. }
  212. if ($caseSensitive) {
  213. // Warning check, see http://php.net/manual/en/function.substr-compare.php#refsect1-function.substr-compare-returnvalues
  214. if (static::byteLength($string) < $bytes) {
  215. return false;
  216. }
  217. return substr_compare($string, $with, -$bytes, $bytes) === 0;
  218. } else {
  219. return mb_strtolower(mb_substr($string, -$bytes, mb_strlen($string, '8bit'), '8bit'), Yii::$app->charset) === mb_strtolower($with, Yii::$app->charset);
  220. }
  221. }
  222. /**
  223. * Explodes string into array, optionally trims values and skips empty ones
  224. *
  225. * @param string $string String to be exploded.
  226. * @param string $delimiter Delimiter. Default is ','.
  227. * @param mixed $trim Whether to trim each element. Can be:
  228. * - boolean - to trim normally;
  229. * - string - custom characters to trim. Will be passed as a second argument to `trim()` function.
  230. * - callable - will be called for each value instead of trim. Takes the only argument - value.
  231. * @param boolean $skipEmpty Whether to skip empty strings between delimiters. Default is false.
  232. * @return array
  233. * @since 2.0.4
  234. */
  235. public static function explode($string, $delimiter = ',', $trim = true, $skipEmpty = false)
  236. {
  237. $result = explode($delimiter, $string);
  238. if ($trim) {
  239. if ($trim === true) {
  240. $trim = 'trim';
  241. } elseif (!is_callable($trim)) {
  242. $trim = function ($v) use ($trim) {
  243. return trim($v, $trim);
  244. };
  245. }
  246. $result = array_map($trim, $result);
  247. }
  248. if ($skipEmpty) {
  249. // Wrapped with array_values to make array keys sequential after empty values removing
  250. $result = array_values(array_filter($result, function ($value) {
  251. return $value !== '';
  252. }));
  253. }
  254. return $result;
  255. }
  256. /**
  257. * Counts words in a string
  258. * @since 2.0.8
  259. *
  260. * @param string $string
  261. * @return integer
  262. */
  263. public static function countWords($string)
  264. {
  265. return count(preg_split('/\s+/u', $string, null, PREG_SPLIT_NO_EMPTY));
  266. }
  267. }