String.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  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 array|integer $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. * - `regex` a custom regex rule that is ued to match words, default is '|$tag|iu'
  338. *
  339. * @param string $text Text to search the phrase in
  340. * @param string $phrase The phrase that will be searched
  341. * @param array $options An array of html attributes and options.
  342. * @return string The highlighted text
  343. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::highlight
  344. */
  345. public static function highlight($text, $phrase, $options = array()) {
  346. if (empty($phrase)) {
  347. return $text;
  348. }
  349. $default = array(
  350. 'format' => '<span class="highlight">\1</span>',
  351. 'html' => false,
  352. 'regex' => "|%s|iu"
  353. );
  354. $options = array_merge($default, $options);
  355. extract($options);
  356. if (is_array($phrase)) {
  357. $replace = array();
  358. $with = array();
  359. foreach ($phrase as $key => $segment) {
  360. $segment = '(' . preg_quote($segment, '|') . ')';
  361. if ($html) {
  362. $segment = "(?![^<]+>)$segment(?![^<]+>)";
  363. }
  364. $with[] = (is_array($format)) ? $format[$key] : $format;
  365. $replace[] = sprintf($options['regex'], $segment);
  366. }
  367. return preg_replace($replace, $with, $text);
  368. } else {
  369. $phrase = '(' . preg_quote($phrase, '|') . ')';
  370. if ($html) {
  371. $phrase = "(?![^<]+>)$phrase(?![^<]+>)";
  372. }
  373. return preg_replace(sprintf($options['regex'], $phrase), $format, $text);
  374. }
  375. }
  376. /**
  377. * Strips given text of all links (<a href=....)
  378. *
  379. * @param string $text Text
  380. * @return string The text without links
  381. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::stripLinks
  382. */
  383. public static function stripLinks($text) {
  384. return preg_replace('|<a\s+[^>]+>|im', '', preg_replace('|<\/a>|im', '', $text));
  385. }
  386. /**
  387. * Truncates text starting from the end.
  388. *
  389. * Cuts a string to the length of $length and replaces the first characters
  390. * with the ellipsis if the text is longer than length.
  391. *
  392. * ### Options:
  393. *
  394. * - `ellipsis` Will be used as Beginning and prepended to the trimmed string
  395. * - `exact` If false, $text will not be cut mid-word
  396. *
  397. * @param string $text String to truncate.
  398. * @param integer $length Length of returned string, including ellipsis.
  399. * @param array $options An array of options.
  400. * @return string Trimmed string.
  401. */
  402. public static function tail($text, $length = 100, $options = array()) {
  403. $default = array(
  404. 'ellipsis' => '...', 'exact' => true
  405. );
  406. $options = array_merge($default, $options);
  407. extract($options);
  408. if (!function_exists('mb_strlen')) {
  409. class_exists('Multibyte');
  410. }
  411. if (mb_strlen($text) <= $length) {
  412. return $text;
  413. } else {
  414. $truncate = mb_substr($text, mb_strlen($text) - $length + mb_strlen($ellipsis));
  415. }
  416. if (!$exact) {
  417. $spacepos = mb_strpos($truncate, ' ');
  418. $truncate = $spacepos === false ? '' : trim(mb_substr($truncate, $spacepos));
  419. }
  420. return $ellipsis . $truncate;
  421. }
  422. /**
  423. * Truncates text.
  424. *
  425. * Cuts a string to the length of $length and replaces the last characters
  426. * with the ellipsis if the text is longer than length.
  427. *
  428. * ### Options:
  429. *
  430. * - `ellipsis` Will be used as Ending and appended to the trimmed string (`ending` is deprecated)
  431. * - `exact` If false, $text will not be cut mid-word
  432. * - `html` If true, HTML tags would be handled correctly
  433. *
  434. * @param string $text String to truncate.
  435. * @param integer $length Length of returned string, including ellipsis.
  436. * @param array $options An array of html attributes and options.
  437. * @return string Trimmed string.
  438. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::truncate
  439. */
  440. public static function truncate($text, $length = 100, $options = array()) {
  441. $default = array(
  442. 'ellipsis' => '...', 'exact' => true, 'html' => false
  443. );
  444. if (!empty($options['html'])) {
  445. $default['ellipsis'] = chr(226);
  446. }
  447. if (isset($options['ending'])) {
  448. $default['ellipsis'] = $options['ending'];
  449. }
  450. $options = array_merge($default, $options);
  451. extract($options);
  452. if (!function_exists('mb_strlen')) {
  453. class_exists('Multibyte');
  454. }
  455. if ($html) {
  456. if (mb_strlen(preg_replace('/<.*?>/', '', $text)) <= $length) {
  457. return $text;
  458. }
  459. $totalLength = mb_strlen(strip_tags($ellipsis));
  460. $openTags = array();
  461. $truncate = '';
  462. preg_match_all('/(<\/?([\w+]+)[^>]*>)?([^<>]*)/', $text, $tags, PREG_SET_ORDER);
  463. foreach ($tags as $tag) {
  464. if (!preg_match('/img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param/s', $tag[2])) {
  465. if (preg_match('/<[\w]+[^>]*>/s', $tag[0])) {
  466. array_unshift($openTags, $tag[2]);
  467. } elseif (preg_match('/<\/([\w]+)[^>]*>/s', $tag[0], $closeTag)) {
  468. $pos = array_search($closeTag[1], $openTags);
  469. if ($pos !== false) {
  470. array_splice($openTags, $pos, 1);
  471. }
  472. }
  473. }
  474. $truncate .= $tag[1];
  475. $contentLength = mb_strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $tag[3]));
  476. if ($contentLength + $totalLength > $length) {
  477. $left = $length - $totalLength;
  478. $entitiesLength = 0;
  479. 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)) {
  480. foreach ($entities[0] as $entity) {
  481. if ($entity[1] + 1 - $entitiesLength <= $left) {
  482. $left--;
  483. $entitiesLength += mb_strlen($entity[0]);
  484. } else {
  485. break;
  486. }
  487. }
  488. }
  489. $truncate .= mb_substr($tag[3], 0 , $left + $entitiesLength);
  490. break;
  491. } else {
  492. $truncate .= $tag[3];
  493. $totalLength += $contentLength;
  494. }
  495. if ($totalLength >= $length) {
  496. break;
  497. }
  498. }
  499. } else {
  500. if (mb_strlen($text) <= $length) {
  501. return $text;
  502. } else {
  503. $truncate = mb_substr($text, 0, $length - mb_strlen($ellipsis));
  504. }
  505. }
  506. if (!$exact) {
  507. $spacepos = mb_strrpos($truncate, ' ');
  508. if ($html) {
  509. $truncateCheck = mb_substr($truncate, 0, $spacepos);
  510. $lastOpenTag = mb_strrpos($truncateCheck, '<');
  511. $lastCloseTag = mb_strrpos($truncateCheck, '>');
  512. if ($lastOpenTag > $lastCloseTag) {
  513. preg_match_all('/<[\w]+[^>]*>/s', $truncate, $lastTagMatches);
  514. $lastTag = array_pop($lastTagMatches[0]);
  515. $spacepos = mb_strrpos($truncate, $lastTag) + mb_strlen($lastTag);
  516. }
  517. $bits = mb_substr($truncate, $spacepos);
  518. preg_match_all('/<\/([a-z]+)>/', $bits, $droppedTags, PREG_SET_ORDER);
  519. if (!empty($droppedTags)) {
  520. if (!empty($openTags)) {
  521. foreach ($droppedTags as $closingTag) {
  522. if (!in_array($closingTag[1], $openTags)) {
  523. array_unshift($openTags, $closingTag[1]);
  524. }
  525. }
  526. } else {
  527. foreach ($droppedTags as $closingTag) {
  528. array_push($openTags, $closingTag[1]);
  529. }
  530. }
  531. }
  532. }
  533. $truncate = mb_substr($truncate, 0, $spacepos);
  534. }
  535. $truncate .= $ellipsis;
  536. if ($html) {
  537. foreach ($openTags as $tag) {
  538. $truncate .= '</' . $tag . '>';
  539. }
  540. }
  541. return $truncate;
  542. }
  543. /**
  544. * Extracts an excerpt from the text surrounding the phrase with a number of characters on each side
  545. * determined by radius.
  546. *
  547. * @param string $text String to search the phrase in
  548. * @param string $phrase Phrase that will be searched for
  549. * @param integer $radius The amount of characters that will be returned on each side of the founded phrase
  550. * @param string $ellipsis Ending that will be appended
  551. * @return string Modified string
  552. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::excerpt
  553. */
  554. public static function excerpt($text, $phrase, $radius = 100, $ellipsis = '...') {
  555. if (empty($text) || empty($phrase)) {
  556. return self::truncate($text, $radius * 2, array('ellipsis' => $ellipsis));
  557. }
  558. $append = $prepend = $ellipsis;
  559. $phraseLen = mb_strlen($phrase);
  560. $textLen = mb_strlen($text);
  561. $pos = mb_strpos(mb_strtolower($text), mb_strtolower($phrase));
  562. if ($pos === false) {
  563. return mb_substr($text, 0, $radius) . $ellipsis;
  564. }
  565. $startPos = $pos - $radius;
  566. if ($startPos <= 0) {
  567. $startPos = 0;
  568. $prepend = '';
  569. }
  570. $endPos = $pos + $phraseLen + $radius;
  571. if ($endPos >= $textLen) {
  572. $endPos = $textLen;
  573. $append = '';
  574. }
  575. $excerpt = mb_substr($text, $startPos, $endPos - $startPos);
  576. $excerpt = $prepend . $excerpt . $append;
  577. return $excerpt;
  578. }
  579. /**
  580. * Creates a comma separated list where the last two items are joined with 'and', forming natural English
  581. *
  582. * @param array $list The list to be joined
  583. * @param string $and The word used to join the last and second last items together with. Defaults to 'and'
  584. * @param string $separator The separator used to join all the other items together. Defaults to ', '
  585. * @return string The glued together string.
  586. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::toList
  587. */
  588. public static function toList($list, $and = 'and', $separator = ', ') {
  589. if (count($list) > 1) {
  590. return implode($separator, array_slice($list, null, -1)) . ' ' . $and . ' ' . array_pop($list);
  591. } else {
  592. return array_pop($list);
  593. }
  594. }
  595. }