PageRenderTime 40ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Utility/String.php

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