Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

238 lines
9.4KB

  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 self::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 self::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. $lexer = \HTMLPurifier_Lexer::create($config);
  144. $tokens = $lexer->tokenizeHTML($string, $config, null);
  145. $openTokens = 0;
  146. $totalCount = 0;
  147. $truncated = [];
  148. foreach ($tokens as $token) {
  149. if ($token instanceof \HTMLPurifier_Token_Start) { //Tag begins
  150. $openTokens++;
  151. $truncated[] = $token;
  152. } else if ($token instanceof \HTMLPurifier_Token_Text && $totalCount <= $count) { //Text
  153. if (false === $encoding) {
  154. $token->data = self::truncateWords($token->data, $count - $totalCount, '');
  155. $currentCount = str_word_count($token->data);
  156. } else {
  157. $token->data = self::truncate($token->data, $count - $totalCount, '', $encoding) . ' ';
  158. $currentCount = mb_strlen($token->data, $encoding);
  159. }
  160. $totalCount += $currentCount;
  161. if (1 === $currentCount) {
  162. $token->data = ' ' . $token->data;
  163. }
  164. $truncated[] = $token;
  165. } else if ($token instanceof \HTMLPurifier_Token_End) { //Tag ends
  166. $openTokens--;
  167. $truncated[] = $token;
  168. } else if ($token instanceof \HTMLPurifier_Token_Empty) { //Self contained tags, i.e. <img/> etc.
  169. $truncated[] = $token;
  170. }
  171. if (0 === $openTokens && $totalCount >= $count) {
  172. break;
  173. }
  174. }
  175. $context = new \HTMLPurifier_Context();
  176. $generator = new \HTMLPurifier_Generator($config, $context);
  177. return $generator->generateFromTokens($truncated) . $suffix;
  178. }
  179. /**
  180. * Check if given string starts with specified substring.
  181. * Binary and multibyte safe.
  182. *
  183. * @param string $string Input string
  184. * @param string $with Part to search
  185. * @param boolean $caseSensitive Case sensitive search. Default is true.
  186. * @return boolean Returns true if first input starts with second input, false otherwise
  187. */
  188. public static function startsWith($string, $with, $caseSensitive = true)
  189. {
  190. if (!$bytes = static::byteLength($with)) {
  191. return true;
  192. }
  193. if ($caseSensitive) {
  194. return strncmp($string, $with, $bytes) === 0;
  195. } else {
  196. return mb_strtolower(mb_substr($string, 0, $bytes, '8bit'), Yii::$app->charset) === mb_strtolower($with, Yii::$app->charset);
  197. }
  198. }
  199. /**
  200. * Check if given string ends with specified substring.
  201. * Binary and multibyte safe.
  202. *
  203. * @param string $string
  204. * @param string $with
  205. * @param boolean $caseSensitive Case sensitive search. Default is true.
  206. * @return boolean Returns true if first input ends with second input, false otherwise
  207. */
  208. public static function endsWith($string, $with, $caseSensitive = true)
  209. {
  210. if (!$bytes = static::byteLength($with)) {
  211. return true;
  212. }
  213. if ($caseSensitive) {
  214. // Warning check, see http://php.net/manual/en/function.substr-compare.php#refsect1-function.substr-compare-returnvalues
  215. if (static::byteLength($string) < $bytes) {
  216. return false;
  217. }
  218. return substr_compare($string, $with, -$bytes, $bytes) === 0;
  219. } else {
  220. return mb_strtolower(mb_substr($string, -$bytes, null, '8bit'), Yii::$app->charset) === mb_strtolower($with, Yii::$app->charset);
  221. }
  222. }
  223. }