PageRenderTime 49ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/cake/libs/view/helpers/text.php

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