TextHelper.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. <?php
  2. /**
  3. * Text Helper
  4. *
  5. * Text manipulations: Highlight, excerpt, truncate, strip of links, convert email addresses to mailto: links...
  6. *
  7. * PHP 5
  8. *
  9. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  10. * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. *
  12. * Licensed under The MIT License
  13. * Redistributions of files must retain the above copyright notice.
  14. *
  15. * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  16. * @link http://cakephp.org CakePHP(tm) Project
  17. * @package Cake.View.Helper
  18. * @since CakePHP(tm) v 0.10.0.1076
  19. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  20. */
  21. /**
  22. * Included libraries.
  23. *
  24. */
  25. App::uses('AppHelper', 'View/Helper');
  26. App::uses('HtmlHelper', 'Helper');
  27. App::uses('Multibyte', 'I18n');
  28. /**
  29. * Text helper library.
  30. *
  31. * Text manipulations: Highlight, excerpt, truncate, strip of links, convert email addresses to mailto: links...
  32. *
  33. * @package Cake.View.Helper
  34. * @property HtmlHelper $Html
  35. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html
  36. */
  37. class TextHelper extends AppHelper {
  38. /**
  39. * helpers
  40. *
  41. * @var array
  42. */
  43. public $helpers = array('Html');
  44. /**
  45. * Highlights a given phrase in a text. You can specify any expression in highlighter that
  46. * may include the \1 expression to include the $phrase found.
  47. *
  48. * ### Options:
  49. *
  50. * - `format` The piece of html with that the phrase will be highlighted
  51. * - `html` If true, will ignore any HTML tags, ensuring that only the correct text is highlighted
  52. *
  53. * @param string $text Text to search the phrase in
  54. * @param string $phrase The phrase that will be searched
  55. * @param array $options An array of html attributes and options.
  56. * @return string The highlighted text
  57. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::highlight
  58. */
  59. public function highlight($text, $phrase, $options = array()) {
  60. if (empty($phrase)) {
  61. return $text;
  62. }
  63. $default = array(
  64. 'format' => '<span class="highlight">\1</span>',
  65. 'html' => false
  66. );
  67. $options = array_merge($default, $options);
  68. extract($options);
  69. if (is_array($phrase)) {
  70. $replace = array();
  71. $with = array();
  72. foreach ($phrase as $key => $segment) {
  73. $segment = '(' . preg_quote($segment, '|') . ')';
  74. if ($html) {
  75. $segment = "(?![^<]+>)$segment(?![^<]+>)";
  76. }
  77. $with[] = (is_array($format)) ? $format[$key] : $format;
  78. $replace[] = "|$segment|iu";
  79. }
  80. return preg_replace($replace, $with, $text);
  81. } else {
  82. $phrase = '(' . preg_quote($phrase, '|') . ')';
  83. if ($html) {
  84. $phrase = "(?![^<]+>)$phrase(?![^<]+>)";
  85. }
  86. return preg_replace("|$phrase|iu", $format, $text);
  87. }
  88. }
  89. /**
  90. * Strips given text of all links (<a href=....)
  91. *
  92. * @param string $text Text
  93. * @return string The text without links
  94. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::stripLinks
  95. */
  96. public function stripLinks($text) {
  97. return preg_replace('|<a\s+[^>]+>|im', '', preg_replace('|<\/a>|im', '', $text));
  98. }
  99. /**
  100. * Adds links (<a href=....) to a given text, by finding text that begins with
  101. * strings like http:// and ftp://.
  102. *
  103. * @param string $text Text to add links to
  104. * @param array $htmlOptions Array of HTML options.
  105. * @return string The text with links
  106. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::autoLinkUrls
  107. */
  108. public function autoLinkUrls($text, $htmlOptions = array()) {
  109. $this->_linkOptions = $htmlOptions;
  110. $text = preg_replace_callback(
  111. '#(?<!href="|src="|">)((?:https?|ftp|nntp)://[^\s<>()]+)#i',
  112. array(&$this, '_linkBareUrl'),
  113. $text
  114. );
  115. return preg_replace_callback(
  116. '#(?<!href="|">)(?<!http://|https://|ftp://|nntp://)(www\.[^\n\%\ <]+[^<\n\%\,\.\ <])(?<!\))#i',
  117. array(&$this, '_linkUrls'),
  118. $text
  119. );
  120. }
  121. /**
  122. * Links urls that include http://
  123. *
  124. * @param array $matches
  125. * @return string
  126. * @see TextHelper::autoLinkUrls()
  127. */
  128. protected function _linkBareUrl($matches) {
  129. return $this->Html->link($matches[0], $matches[0], $this->_linkOptions);
  130. }
  131. /**
  132. * Links urls missing http://
  133. *
  134. * @param array $matches
  135. * @return string
  136. * @see TextHelper::autoLinkUrls()
  137. */
  138. protected function _linkUrls($matches) {
  139. return $this->Html->link($matches[0], 'http://' . $matches[0], $this->_linkOptions);
  140. }
  141. /**
  142. * Links email addresses
  143. *
  144. * @param array $matches
  145. * @return string
  146. * @see TextHelper::autoLinkUrls()
  147. */
  148. protected function _linkEmails($matches) {
  149. return $this->Html->link($matches[0], 'mailto:' . $matches[0], $this->_linkOptions);
  150. }
  151. /**
  152. * Adds email links (<a href="mailto:....) to a given text.
  153. *
  154. * @param string $text Text
  155. * @param array $options Array of HTML options.
  156. * @return string The text with links
  157. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::autoLinkEmails
  158. */
  159. public function autoLinkEmails($text, $options = array()) {
  160. $this->_linkOptions = $options;
  161. $atom = '[a-z0-9!#$%&\'*+\/=?^_`{|}~-]';
  162. return preg_replace_callback(
  163. '/(' . $atom . '+(?:\.' . $atom . '+)*@[a-z0-9-]+(?:\.[a-z0-9-]+)+)/i',
  164. array(&$this, '_linkEmails'),
  165. $text
  166. );
  167. }
  168. /**
  169. * Convert all links and email addresses to HTML links.
  170. *
  171. * @param string $text Text
  172. * @param array $options Array of HTML options.
  173. * @return string The text with links
  174. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::autoLink
  175. */
  176. public function autoLink($text, $options = array()) {
  177. return $this->autoLinkEmails($this->autoLinkUrls($text, $options), $options);
  178. }
  179. /**
  180. * Truncates text.
  181. *
  182. * Cuts a string to the length of $length and replaces the last characters
  183. * with the ending if the text is longer than length.
  184. *
  185. * ### Options:
  186. *
  187. * - `ending` Will be used as Ending and appended to the trimmed string
  188. * - `exact` If false, $text will not be cut mid-word
  189. * - `html` If true, HTML tags would be handled correctly
  190. *
  191. * @param string $text String to truncate.
  192. * @param integer $length Length of returned string, including ellipsis.
  193. * @param array $options An array of html attributes and options.
  194. * @return string Trimmed string.
  195. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::truncate
  196. */
  197. public function truncate($text, $length = 100, $options = array()) {
  198. $default = array(
  199. 'ending' => '...', 'exact' => true, 'html' => false
  200. );
  201. $options = array_merge($default, $options);
  202. extract($options);
  203. if (!function_exists('mb_strlen')) {
  204. class_exists('Multibyte');
  205. }
  206. if ($html) {
  207. if (mb_strlen(preg_replace('/<.*?>/', '', $text)) <= $length) {
  208. return $text;
  209. }
  210. $totalLength = mb_strlen(strip_tags($ending));
  211. $openTags = array();
  212. $truncate = '';
  213. preg_match_all('/(<\/?([\w+]+)[^>]*>)?([^<>]*)/', $text, $tags, PREG_SET_ORDER);
  214. foreach ($tags as $tag) {
  215. if (!preg_match('/img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param/s', $tag[2])) {
  216. if (preg_match('/<[\w]+[^>]*>/s', $tag[0])) {
  217. array_unshift($openTags, $tag[2]);
  218. } else if (preg_match('/<\/([\w]+)[^>]*>/s', $tag[0], $closeTag)) {
  219. $pos = array_search($closeTag[1], $openTags);
  220. if ($pos !== false) {
  221. array_splice($openTags, $pos, 1);
  222. }
  223. }
  224. }
  225. $truncate .= $tag[1];
  226. $contentLength = mb_strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $tag[3]));
  227. if ($contentLength + $totalLength > $length) {
  228. $left = $length - $totalLength;
  229. $entitiesLength = 0;
  230. 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)) {
  231. foreach ($entities[0] as $entity) {
  232. if ($entity[1] + 1 - $entitiesLength <= $left) {
  233. $left--;
  234. $entitiesLength += mb_strlen($entity[0]);
  235. } else {
  236. break;
  237. }
  238. }
  239. }
  240. $truncate .= mb_substr($tag[3], 0 , $left + $entitiesLength);
  241. break;
  242. } else {
  243. $truncate .= $tag[3];
  244. $totalLength += $contentLength;
  245. }
  246. if ($totalLength >= $length) {
  247. break;
  248. }
  249. }
  250. } else {
  251. if (mb_strlen($text) <= $length) {
  252. return $text;
  253. } else {
  254. $truncate = mb_substr($text, 0, $length - mb_strlen($ending));
  255. }
  256. }
  257. if (!$exact) {
  258. $spacepos = mb_strrpos($truncate, ' ');
  259. if (isset($spacepos)) {
  260. if ($html) {
  261. $bits = mb_substr($truncate, $spacepos);
  262. preg_match_all('/<\/([a-z]+)>/', $bits, $droppedTags, PREG_SET_ORDER);
  263. if (!empty($droppedTags)) {
  264. foreach ($droppedTags as $closingTag) {
  265. if (!in_array($closingTag[1], $openTags)) {
  266. array_unshift($openTags, $closingTag[1]);
  267. }
  268. }
  269. }
  270. }
  271. $truncate = mb_substr($truncate, 0, $spacepos);
  272. }
  273. }
  274. $truncate .= $ending;
  275. if ($html) {
  276. foreach ($openTags as $tag) {
  277. $truncate .= '</'.$tag.'>';
  278. }
  279. }
  280. return $truncate;
  281. }
  282. /**
  283. * Extracts an excerpt from the text surrounding the phrase with a number of characters on each side
  284. * determined by radius.
  285. *
  286. * @param string $text String to search the phrase in
  287. * @param string $phrase Phrase that will be searched for
  288. * @param integer $radius The amount of characters that will be returned on each side of the founded phrase
  289. * @param string $ending Ending that will be appended
  290. * @return string Modified string
  291. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::excerpt
  292. */
  293. public function excerpt($text, $phrase, $radius = 100, $ending = '...') {
  294. if (empty($text) or empty($phrase)) {
  295. return $this->truncate($text, $radius * 2, array('ending' => $ending));
  296. }
  297. $append = $prepend = $ending;
  298. $phraseLen = mb_strlen($phrase);
  299. $textLen = mb_strlen($text);
  300. $pos = mb_strpos(mb_strtolower($text), mb_strtolower($phrase));
  301. if ($pos === false) {
  302. return mb_substr($text, 0, $radius) . $ending;
  303. }
  304. $startPos = $pos - $radius;
  305. if ($startPos <= 0) {
  306. $startPos = 0;
  307. $prepend = '';
  308. }
  309. $endPos = $pos + $phraseLen + $radius;
  310. if ($endPos >= $textLen) {
  311. $endPos = $textLen;
  312. $append = '';
  313. }
  314. $excerpt = mb_substr($text, $startPos, $endPos - $startPos);
  315. $excerpt = $prepend . $excerpt . $append;
  316. return $excerpt;
  317. }
  318. /**
  319. * Creates a comma separated list where the last two items are joined with 'and', forming natural English
  320. *
  321. * @param array $list The list to be joined
  322. * @param string $and The word used to join the last and second last items together with. Defaults to 'and'
  323. * @param string $separator The separator used to join all the other items together. Defaults to ', '
  324. * @return string The glued together string.
  325. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::toList
  326. */
  327. public function toList($list, $and = 'and', $separator = ', ') {
  328. if (count($list) > 1) {
  329. return implode($separator, array_slice($list, null, -1)) . ' ' . $and . ' ' . array_pop($list);
  330. } else {
  331. return array_pop($list);
  332. }
  333. }
  334. }