PageRenderTime 67ms CodeModel.GetById 37ms RepoModel.GetById 0ms app.codeStats 0ms

/Vendor/pear-pear.cakephp.org/CakePHP/Cake/Utility/String.php

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