PageRenderTime 60ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/Cake/Utility/String.php

https://bitbucket.org/npavlicevic/cakeblog_new
PHP | 643 lines | 531 code | 31 blank | 81 comment | 64 complexity | d8353fd255cf1d8ce58c1944ccf5be7f MD5 | raw file
  1. <?php
  2. /**
  3. * String handling methods.
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * For full copyright and license information, please see the LICENSE.txt
  12. * Redistributions of files must retain the above copyright notice.
  13. *
  14. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  15. * @link http://cakephp.org CakePHP(tm) Project
  16. * @package Cake.Utility
  17. * @since CakePHP(tm) v 1.2.0.5551
  18. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  19. */
  20. /**
  21. * String handling methods.
  22. *
  23. *
  24. * @package Cake.Utility
  25. */
  26. class String {
  27. /**
  28. * Generate a random UUID
  29. *
  30. * @see http://www.ietf.org/rfc/rfc4122.txt
  31. * @return RFC 4122 UUID
  32. */
  33. public static function uuid() {
  34. $node = env('SERVER_ADDR');
  35. if (strpos($node, ':') !== false) {
  36. if (substr_count($node, '::')) {
  37. $node = str_replace(
  38. '::', str_repeat(':0000', 8 - substr_count($node, ':')) . ':', $node
  39. );
  40. }
  41. $node = explode(':', $node);
  42. $ipSix = '';
  43. foreach ($node as $id) {
  44. $ipSix .= str_pad(base_convert($id, 16, 2), 16, 0, STR_PAD_LEFT);
  45. }
  46. $node = base_convert($ipSix, 2, 10);
  47. if (strlen($node) < 38) {
  48. $node = null;
  49. } else {
  50. $node = crc32($node);
  51. }
  52. } elseif (empty($node)) {
  53. $host = env('HOSTNAME');
  54. if (empty($host)) {
  55. $host = env('HOST');
  56. }
  57. if (!empty($host)) {
  58. $ip = gethostbyname($host);
  59. if ($ip === $host) {
  60. $node = crc32($host);
  61. } else {
  62. $node = ip2long($ip);
  63. }
  64. }
  65. } elseif ($node !== '127.0.0.1') {
  66. $node = ip2long($node);
  67. } else {
  68. $node = null;
  69. }
  70. if (empty($node)) {
  71. $node = crc32(Configure::read('Security.salt'));
  72. }
  73. if (function_exists('hphp_get_thread_id')) {
  74. $pid = hphp_get_thread_id();
  75. } elseif (function_exists('zend_thread_id')) {
  76. $pid = zend_thread_id();
  77. } else {
  78. $pid = getmypid();
  79. }
  80. if (!$pid || $pid > 65535) {
  81. $pid = mt_rand(0, 0xfff) | 0x4000;
  82. }
  83. list($timeMid, $timeLow) = explode(' ', microtime());
  84. return sprintf(
  85. "%08x-%04x-%04x-%02x%02x-%04x%08x", (int)$timeLow, (int)substr($timeMid, 2) & 0xffff,
  86. mt_rand(0, 0xfff) | 0x4000, mt_rand(0, 0x3f) | 0x80, mt_rand(0, 0xff), $pid, $node
  87. );
  88. }
  89. /**
  90. * Tokenizes a string using $separator, ignoring any instance of $separator that appears between
  91. * $leftBound and $rightBound
  92. *
  93. * @param string $data The data to tokenize
  94. * @param string $separator The token to split the data on.
  95. * @param string $leftBound The left boundary to ignore separators in.
  96. * @param string $rightBound The right boundary to ignore separators in.
  97. * @return array Array of tokens in $data.
  98. */
  99. public static function tokenize($data, $separator = ',', $leftBound = '(', $rightBound = ')') {
  100. if (empty($data) || is_array($data)) {
  101. return $data;
  102. }
  103. $depth = 0;
  104. $offset = 0;
  105. $buffer = '';
  106. $results = array();
  107. $length = strlen($data);
  108. $open = false;
  109. while ($offset <= $length) {
  110. $tmpOffset = -1;
  111. $offsets = array(
  112. strpos($data, $separator, $offset),
  113. strpos($data, $leftBound, $offset),
  114. strpos($data, $rightBound, $offset)
  115. );
  116. for ($i = 0; $i < 3; $i++) {
  117. if ($offsets[$i] !== false && ($offsets[$i] < $tmpOffset || $tmpOffset == -1)) {
  118. $tmpOffset = $offsets[$i];
  119. }
  120. }
  121. if ($tmpOffset !== -1) {
  122. $buffer .= substr($data, $offset, ($tmpOffset - $offset));
  123. if (!$depth && $data{$tmpOffset} == $separator) {
  124. $results[] = $buffer;
  125. $buffer = '';
  126. } else {
  127. $buffer .= $data{$tmpOffset};
  128. }
  129. if ($leftBound != $rightBound) {
  130. if ($data{$tmpOffset} == $leftBound) {
  131. $depth++;
  132. }
  133. if ($data{$tmpOffset} == $rightBound) {
  134. $depth--;
  135. }
  136. } else {
  137. if ($data{$tmpOffset} == $leftBound) {
  138. if (!$open) {
  139. $depth++;
  140. $open = true;
  141. } else {
  142. $depth--;
  143. }
  144. }
  145. }
  146. $offset = ++$tmpOffset;
  147. } else {
  148. $results[] = $buffer . substr($data, $offset);
  149. $offset = $length + 1;
  150. }
  151. }
  152. if (empty($results) && !empty($buffer)) {
  153. $results[] = $buffer;
  154. }
  155. if (!empty($results)) {
  156. return array_map('trim', $results);
  157. }
  158. return array();
  159. }
  160. /**
  161. * Replaces variable placeholders inside a $str with any given $data. Each key in the $data array
  162. * corresponds to a variable placeholder name in $str.
  163. * Example: `String::insert(':name is :age years old.', array('name' => 'Bob', '65'));`
  164. * Returns: Bob is 65 years old.
  165. *
  166. * Available $options are:
  167. *
  168. * - before: The character or string in front of the name of the variable placeholder (Defaults to `:`)
  169. * - after: The character or string after the name of the variable placeholder (Defaults to null)
  170. * - escape: The character or string used to escape the before character / string (Defaults to `\`)
  171. * - format: A regex to use for matching variable placeholders. Default is: `/(?<!\\)\:%s/`
  172. * (Overwrites before, after, breaks escape / clean)
  173. * - clean: A boolean or array with instructions for String::cleanInsert
  174. *
  175. * @param string $str A string containing variable placeholders
  176. * @param string $data A key => val array where each key stands for a placeholder variable name
  177. * to be replaced with val
  178. * @param string $options An array of options, see description above
  179. * @return string
  180. */
  181. public static function insert($str, $data, $options = array()) {
  182. $defaults = array(
  183. 'before' => ':', 'after' => null, 'escape' => '\\', 'format' => null, 'clean' => false
  184. );
  185. $options += $defaults;
  186. $format = $options['format'];
  187. $data = (array)$data;
  188. if (empty($data)) {
  189. return ($options['clean']) ? String::cleanInsert($str, $options) : $str;
  190. }
  191. if (!isset($format)) {
  192. $format = sprintf(
  193. '/(?<!%s)%s%%s%s/',
  194. preg_quote($options['escape'], '/'),
  195. str_replace('%', '%%', preg_quote($options['before'], '/')),
  196. str_replace('%', '%%', preg_quote($options['after'], '/'))
  197. );
  198. }
  199. if (strpos($str, '?') !== false && is_numeric(key($data))) {
  200. $offset = 0;
  201. while (($pos = strpos($str, '?', $offset)) !== false) {
  202. $val = array_shift($data);
  203. $offset = $pos + strlen($val);
  204. $str = substr_replace($str, $val, $pos, 1);
  205. }
  206. return ($options['clean']) ? String::cleanInsert($str, $options) : $str;
  207. }
  208. asort($data);
  209. $dataKeys = array_keys($data);
  210. $hashKeys = array_map('crc32', $dataKeys);
  211. $tempData = array_combine($dataKeys, $hashKeys);
  212. krsort($tempData);
  213. foreach ($tempData as $key => $hashVal) {
  214. $key = sprintf($format, preg_quote($key, '/'));
  215. $str = preg_replace($key, $hashVal, $str);
  216. }
  217. $dataReplacements = array_combine($hashKeys, array_values($data));
  218. foreach ($dataReplacements as $tmpHash => $tmpValue) {
  219. $tmpValue = (is_array($tmpValue)) ? '' : $tmpValue;
  220. $str = str_replace($tmpHash, $tmpValue, $str);
  221. }
  222. if (!isset($options['format']) && isset($options['before'])) {
  223. $str = str_replace($options['escape'] . $options['before'], $options['before'], $str);
  224. }
  225. return ($options['clean']) ? String::cleanInsert($str, $options) : $str;
  226. }
  227. /**
  228. * Cleans up a String::insert() formatted string with given $options depending on the 'clean' key in
  229. * $options. The default method used is text but html is also available. The goal of this function
  230. * is to replace all whitespace and unneeded markup around placeholders that did not get replaced
  231. * by String::insert().
  232. *
  233. * @param string $str
  234. * @param string $options
  235. * @return string
  236. * @see String::insert()
  237. */
  238. public static function cleanInsert($str, $options) {
  239. $clean = $options['clean'];
  240. if (!$clean) {
  241. return $str;
  242. }
  243. if ($clean === true) {
  244. $clean = array('method' => 'text');
  245. }
  246. if (!is_array($clean)) {
  247. $clean = array('method' => $options['clean']);
  248. }
  249. switch ($clean['method']) {
  250. case 'html':
  251. $clean = array_merge(array(
  252. 'word' => '[\w,.]+',
  253. 'andText' => true,
  254. 'replacement' => '',
  255. ), $clean);
  256. $kleenex = sprintf(
  257. '/[\s]*[a-z]+=(")(%s%s%s[\s]*)+\\1/i',
  258. preg_quote($options['before'], '/'),
  259. $clean['word'],
  260. preg_quote($options['after'], '/')
  261. );
  262. $str = preg_replace($kleenex, $clean['replacement'], $str);
  263. if ($clean['andText']) {
  264. $options['clean'] = array('method' => 'text');
  265. $str = String::cleanInsert($str, $options);
  266. }
  267. break;
  268. case 'text':
  269. $clean = array_merge(array(
  270. 'word' => '[\w,.]+',
  271. 'gap' => '[\s]*(?:(?:and|or)[\s]*)?',
  272. 'replacement' => '',
  273. ), $clean);
  274. $kleenex = sprintf(
  275. '/(%s%s%s%s|%s%s%s%s)/',
  276. preg_quote($options['before'], '/'),
  277. $clean['word'],
  278. preg_quote($options['after'], '/'),
  279. $clean['gap'],
  280. $clean['gap'],
  281. preg_quote($options['before'], '/'),
  282. $clean['word'],
  283. preg_quote($options['after'], '/')
  284. );
  285. $str = preg_replace($kleenex, $clean['replacement'], $str);
  286. break;
  287. }
  288. return $str;
  289. }
  290. /**
  291. * Wraps text to a specific width, can optionally wrap at word breaks.
  292. *
  293. * ### Options
  294. *
  295. * - `width` The width to wrap to. Defaults to 72
  296. * - `wordWrap` Only wrap on words breaks (spaces) Defaults to true.
  297. * - `indent` String to indent with. Defaults to null.
  298. * - `indentAt` 0 based index to start indenting at. Defaults to 0.
  299. *
  300. * @param string $text Text the text to format.
  301. * @param array|integer $options Array of options to use, or an integer to wrap the text to.
  302. * @return string Formatted text.
  303. */
  304. public static function wrap($text, $options = array()) {
  305. if (is_numeric($options)) {
  306. $options = array('width' => $options);
  307. }
  308. $options += array('width' => 72, 'wordWrap' => true, 'indent' => null, 'indentAt' => 0);
  309. if ($options['wordWrap']) {
  310. $wrapped = wordwrap($text, $options['width'], "\n");
  311. } else {
  312. $wrapped = trim(chunk_split($text, $options['width'] - 1, "\n"));
  313. }
  314. if (!empty($options['indent'])) {
  315. $chunks = explode("\n", $wrapped);
  316. for ($i = $options['indentAt'], $len = count($chunks); $i < $len; $i++) {
  317. $chunks[$i] = $options['indent'] . $chunks[$i];
  318. }
  319. $wrapped = implode("\n", $chunks);
  320. }
  321. return $wrapped;
  322. }
  323. /**
  324. * Highlights a given phrase in a text. You can specify any expression in highlighter that
  325. * may include the \1 expression to include the $phrase found.
  326. *
  327. * ### Options:
  328. *
  329. * - `format` The piece of html with that the phrase will be highlighted
  330. * - `html` If true, will ignore any HTML tags, ensuring that only the correct text is highlighted
  331. * - `regex` a custom regex rule that is used to match words, default is '|$tag|iu'
  332. *
  333. * @param string $text Text to search the phrase in
  334. * @param string $phrase The phrase that will be searched
  335. * @param array $options An array of html attributes and options.
  336. * @return string The highlighted text
  337. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::highlight
  338. */
  339. public static function highlight($text, $phrase, $options = array()) {
  340. if (empty($phrase)) {
  341. return $text;
  342. }
  343. $default = array(
  344. 'format' => '<span class="highlight">\1</span>',
  345. 'html' => false,
  346. 'regex' => "|%s|iu"
  347. );
  348. $options = array_merge($default, $options);
  349. extract($options);
  350. if (is_array($phrase)) {
  351. $replace = array();
  352. $with = array();
  353. foreach ($phrase as $key => $segment) {
  354. $segment = '(' . preg_quote($segment, '|') . ')';
  355. if ($html) {
  356. $segment = "(?![^<]+>)$segment(?![^<]+>)";
  357. }
  358. $with[] = (is_array($format)) ? $format[$key] : $format;
  359. $replace[] = sprintf($options['regex'], $segment);
  360. }
  361. return preg_replace($replace, $with, $text);
  362. }
  363. $phrase = '(' . preg_quote($phrase, '|') . ')';
  364. if ($html) {
  365. $phrase = "(?![^<]+>)$phrase(?![^<]+>)";
  366. }
  367. return preg_replace(sprintf($options['regex'], $phrase), $format, $text);
  368. }
  369. /**
  370. * Strips given text of all links (<a href=....)
  371. *
  372. * @param string $text Text
  373. * @return string The text without links
  374. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::stripLinks
  375. */
  376. public static function stripLinks($text) {
  377. return preg_replace('|<a\s+[^>]+>|im', '', preg_replace('|<\/a>|im', '', $text));
  378. }
  379. /**
  380. * Truncates text starting from the end.
  381. *
  382. * Cuts a string to the length of $length and replaces the first characters
  383. * with the ellipsis if the text is longer than length.
  384. *
  385. * ### Options:
  386. *
  387. * - `ellipsis` Will be used as Beginning and prepended to the trimmed string
  388. * - `exact` If false, $text will not be cut mid-word
  389. *
  390. * @param string $text String to truncate.
  391. * @param integer $length Length of returned string, including ellipsis.
  392. * @param array $options An array of options.
  393. * @return string Trimmed string.
  394. */
  395. public static function tail($text, $length = 100, $options = array()) {
  396. $default = array(
  397. 'ellipsis' => '...', 'exact' => true
  398. );
  399. $options = array_merge($default, $options);
  400. extract($options);
  401. if (!function_exists('mb_strlen')) {
  402. class_exists('Multibyte');
  403. }
  404. if (mb_strlen($text) <= $length) {
  405. return $text;
  406. }
  407. $truncate = mb_substr($text, mb_strlen($text) - $length + mb_strlen($ellipsis));
  408. if (!$exact) {
  409. $spacepos = mb_strpos($truncate, ' ');
  410. $truncate = $spacepos === false ? '' : trim(mb_substr($truncate, $spacepos));
  411. }
  412. return $ellipsis . $truncate;
  413. }
  414. /**
  415. * Truncates text.
  416. *
  417. * Cuts a string to the length of $length and replaces the last characters
  418. * with the ellipsis if the text is longer than length.
  419. *
  420. * ### Options:
  421. *
  422. * - `ellipsis` Will be used as Ending and appended to the trimmed string (`ending` is deprecated)
  423. * - `exact` If false, $text will not be cut mid-word
  424. * - `html` If true, HTML tags would be handled correctly
  425. *
  426. * @param string $text String to truncate.
  427. * @param integer $length Length of returned string, including ellipsis.
  428. * @param array $options An array of html attributes and options.
  429. * @return string Trimmed string.
  430. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::truncate
  431. */
  432. public static function truncate($text, $length = 100, $options = array()) {
  433. $default = array(
  434. 'ellipsis' => '...', 'exact' => true, 'html' => false
  435. );
  436. if (isset($options['ending'])) {
  437. $default['ellipsis'] = $options['ending'];
  438. } elseif (!empty($options['html']) && Configure::read('App.encoding') === 'UTF-8') {
  439. $default['ellipsis'] = "\xe2\x80\xa6";
  440. }
  441. $options = array_merge($default, $options);
  442. extract($options);
  443. if (!function_exists('mb_strlen')) {
  444. class_exists('Multibyte');
  445. }
  446. if ($html) {
  447. if (mb_strlen(preg_replace('/<.*?>/', '', $text)) <= $length) {
  448. return $text;
  449. }
  450. $totalLength = mb_strlen(strip_tags($ellipsis));
  451. $openTags = array();
  452. $truncate = '';
  453. preg_match_all('/(<\/?([\w+]+)[^>]*>)?([^<>]*)/', $text, $tags, PREG_SET_ORDER);
  454. foreach ($tags as $tag) {
  455. if (!preg_match('/img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param/s', $tag[2])) {
  456. if (preg_match('/<[\w]+[^>]*>/s', $tag[0])) {
  457. array_unshift($openTags, $tag[2]);
  458. } elseif (preg_match('/<\/([\w]+)[^>]*>/s', $tag[0], $closeTag)) {
  459. $pos = array_search($closeTag[1], $openTags);
  460. if ($pos !== false) {
  461. array_splice($openTags, $pos, 1);
  462. }
  463. }
  464. }
  465. $truncate .= $tag[1];
  466. $contentLength = mb_strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $tag[3]));
  467. if ($contentLength + $totalLength > $length) {
  468. $left = $length - $totalLength;
  469. $entitiesLength = 0;
  470. if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', $tag[3], $entities, PREG_OFFSET_CAPTURE)) {
  471. foreach ($entities[0] as $entity) {
  472. if ($entity[1] + 1 - $entitiesLength <= $left) {
  473. $left--;
  474. $entitiesLength += mb_strlen($entity[0]);
  475. } else {
  476. break;
  477. }
  478. }
  479. }
  480. $truncate .= mb_substr($tag[3], 0 , $left + $entitiesLength);
  481. break;
  482. } else {
  483. $truncate .= $tag[3];
  484. $totalLength += $contentLength;
  485. }
  486. if ($totalLength >= $length) {
  487. break;
  488. }
  489. }
  490. } else {
  491. if (mb_strlen($text) <= $length) {
  492. return $text;
  493. }
  494. $truncate = mb_substr($text, 0, $length - mb_strlen($ellipsis));
  495. }
  496. if (!$exact) {
  497. $spacepos = mb_strrpos($truncate, ' ');
  498. if ($html) {
  499. $truncateCheck = mb_substr($truncate, 0, $spacepos);
  500. $lastOpenTag = mb_strrpos($truncateCheck, '<');
  501. $lastCloseTag = mb_strrpos($truncateCheck, '>');
  502. if ($lastOpenTag > $lastCloseTag) {
  503. preg_match_all('/<[\w]+[^>]*>/s', $truncate, $lastTagMatches);
  504. $lastTag = array_pop($lastTagMatches[0]);
  505. $spacepos = mb_strrpos($truncate, $lastTag) + mb_strlen($lastTag);
  506. }
  507. $bits = mb_substr($truncate, $spacepos);
  508. preg_match_all('/<\/([a-z]+)>/', $bits, $droppedTags, PREG_SET_ORDER);
  509. if (!empty($droppedTags)) {
  510. if (!empty($openTags)) {
  511. foreach ($droppedTags as $closingTag) {
  512. if (!in_array($closingTag[1], $openTags)) {
  513. array_unshift($openTags, $closingTag[1]);
  514. }
  515. }
  516. } else {
  517. foreach ($droppedTags as $closingTag) {
  518. $openTags[] = $closingTag[1];
  519. }
  520. }
  521. }
  522. }
  523. $truncate = mb_substr($truncate, 0, $spacepos);
  524. }
  525. $truncate .= $ellipsis;
  526. if ($html) {
  527. foreach ($openTags as $tag) {
  528. $truncate .= '</' . $tag . '>';
  529. }
  530. }
  531. return $truncate;
  532. }
  533. /**
  534. * Extracts an excerpt from the text surrounding the phrase with a number of characters on each side
  535. * determined by radius.
  536. *
  537. * @param string $text String to search the phrase in
  538. * @param string $phrase Phrase that will be searched for
  539. * @param integer $radius The amount of characters that will be returned on each side of the founded phrase
  540. * @param string $ellipsis Ending that will be appended
  541. * @return string Modified string
  542. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::excerpt
  543. */
  544. public static function excerpt($text, $phrase, $radius = 100, $ellipsis = '...') {
  545. if (empty($text) || empty($phrase)) {
  546. return self::truncate($text, $radius * 2, array('ellipsis' => $ellipsis));
  547. }
  548. $append = $prepend = $ellipsis;
  549. $phraseLen = mb_strlen($phrase);
  550. $textLen = mb_strlen($text);
  551. $pos = mb_strpos(mb_strtolower($text), mb_strtolower($phrase));
  552. if ($pos === false) {
  553. return mb_substr($text, 0, $radius) . $ellipsis;
  554. }
  555. $startPos = $pos - $radius;
  556. if ($startPos <= 0) {
  557. $startPos = 0;
  558. $prepend = '';
  559. }
  560. $endPos = $pos + $phraseLen + $radius;
  561. if ($endPos >= $textLen) {
  562. $endPos = $textLen;
  563. $append = '';
  564. }
  565. $excerpt = mb_substr($text, $startPos, $endPos - $startPos);
  566. $excerpt = $prepend . $excerpt . $append;
  567. return $excerpt;
  568. }
  569. /**
  570. * Creates a comma separated list where the last two items are joined with 'and', forming natural English
  571. *
  572. * @param array $list The list to be joined
  573. * @param string $and The word used to join the last and second last items together with. Defaults to 'and'
  574. * @param string $separator The separator used to join all the other items together. Defaults to ', '
  575. * @return string The glued together string.
  576. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::toList
  577. */
  578. public static function toList($list, $and = 'and', $separator = ', ') {
  579. if (count($list) > 1) {
  580. return implode($separator, array_slice($list, null, -1)) . ' ' . $and . ' ' . array_pop($list);
  581. }
  582. return array_pop($list);
  583. }
  584. }