You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

286 satır
11KB

  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 trim(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. $token->data = self::truncateWords($token->data, $count - $totalCount, '');
  156. $currentCount = self::countWords($token->data);
  157. } else {
  158. $token->data = self::truncate($token->data, $count - $totalCount, '', $encoding) . ' ';
  159. $currentCount = mb_strlen($token->data, $encoding);
  160. }
  161. $totalCount += $currentCount;
  162. if (1 === $currentCount) {
  163. $token->data = ' ' . $token->data;
  164. }
  165. $truncated[] = $token;
  166. } elseif ($token instanceof \HTMLPurifier_Token_End) { //Tag ends
  167. $openTokens--;
  168. $truncated[] = $token;
  169. } elseif ($token instanceof \HTMLPurifier_Token_Empty) { //Self contained tags, i.e. <img/> etc.
  170. $truncated[] = $token;
  171. }
  172. if (0 === $openTokens && $totalCount >= $count) {
  173. break;
  174. }
  175. }
  176. $context = new \HTMLPurifier_Context();
  177. $generator = new \HTMLPurifier_Generator($config, $context);
  178. return $generator->generateFromTokens($truncated) . ($totalCount >= $count ? $suffix : '');
  179. }
  180. /**
  181. * Check if given string starts with specified substring.
  182. * Binary and multibyte safe.
  183. *
  184. * @param string $string Input string
  185. * @param string $with Part to search
  186. * @param boolean $caseSensitive Case sensitive search. Default is true.
  187. * @return boolean Returns true if first input starts with second input, false otherwise
  188. */
  189. public static function startsWith($string, $with, $caseSensitive = true)
  190. {
  191. if (!$bytes = static::byteLength($with)) {
  192. return true;
  193. }
  194. if ($caseSensitive) {
  195. return strncmp($string, $with, $bytes) === 0;
  196. } else {
  197. return mb_strtolower(mb_substr($string, 0, $bytes, '8bit'), Yii::$app->charset) === mb_strtolower($with, Yii::$app->charset);
  198. }
  199. }
  200. /**
  201. * Check if given string ends with specified substring.
  202. * Binary and multibyte safe.
  203. *
  204. * @param string $string
  205. * @param string $with
  206. * @param boolean $caseSensitive Case sensitive search. Default is true.
  207. * @return boolean Returns true if first input ends with second input, false otherwise
  208. */
  209. public static function endsWith($string, $with, $caseSensitive = true)
  210. {
  211. if (!$bytes = static::byteLength($with)) {
  212. return true;
  213. }
  214. if ($caseSensitive) {
  215. // Warning check, see http://php.net/manual/en/function.substr-compare.php#refsect1-function.substr-compare-returnvalues
  216. if (static::byteLength($string) < $bytes) {
  217. return false;
  218. }
  219. return substr_compare($string, $with, -$bytes, $bytes) === 0;
  220. } else {
  221. return mb_strtolower(mb_substr($string, -$bytes, mb_strlen($string, '8bit'), '8bit'), Yii::$app->charset) === mb_strtolower($with, Yii::$app->charset);
  222. }
  223. }
  224. /**
  225. * Explodes string into array, optionally trims values and skips empty ones
  226. *
  227. * @param string $string String to be exploded.
  228. * @param string $delimiter Delimiter. Default is ','.
  229. * @param mixed $trim Whether to trim each element. Can be:
  230. * - boolean - to trim normally;
  231. * - string - custom characters to trim. Will be passed as a second argument to `trim()` function.
  232. * - callable - will be called for each value instead of trim. Takes the only argument - value.
  233. * @param boolean $skipEmpty Whether to skip empty strings between delimiters. Default is false.
  234. * @return array
  235. * @since 2.0.4
  236. */
  237. public static function explode($string, $delimiter = ',', $trim = true, $skipEmpty = false)
  238. {
  239. $result = explode($delimiter, $string);
  240. if ($trim) {
  241. if ($trim === true) {
  242. $trim = 'trim';
  243. } elseif (!is_callable($trim)) {
  244. $trim = function ($v) use ($trim) {
  245. return trim($v, $trim);
  246. };
  247. }
  248. $result = array_map($trim, $result);
  249. }
  250. if ($skipEmpty) {
  251. // Wrapped with array_values to make array keys sequential after empty values removing
  252. $result = array_values(array_filter($result, function ($value) {
  253. return $value !== '';
  254. }));
  255. }
  256. return $result;
  257. }
  258. /**
  259. * Counts words in a string
  260. * @since 2.0.8
  261. *
  262. * @param string $string
  263. * @return integer
  264. */
  265. public static function countWords($string)
  266. {
  267. return count(preg_split('/\s+/u', $string, null, PREG_SPLIT_NO_EMPTY));
  268. }
  269. }