CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Reporting Security Issues
    • Privacy Policy
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Get Involved
    • Issues (GitHub)
    • Bakery
    • Featured Resources
    • Training
    • Meetups
    • My CakePHP
    • CakeFest
    • Newsletter
    • Linkedin
    • YouTube
    • Facebook
    • Twitter
    • Mastodon
    • Help & Support
    • Forum
    • Stack Overflow
    • Slack
    • Paid Support
CakePHP

C CakePHP 1.2 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 1.2
      • 4.2
      • 4.1
      • 4.0
      • 3.9
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Classes

  • AclBase
  • AclBehavior
  • AclComponent
  • AclNode
  • AclShell
  • Aco
  • AcoAction
  • AjaxHelper
  • ApcEngine
  • ApiShell
  • App
  • AppController
  • AppHelper
  • AppModel
  • Aro
  • AuthComponent
  • BakeShell
  • BehaviorCollection
  • Cache
  • CacheEngine
  • CacheHelper
  • CakeErrorController
  • CakeLog
  • CakeSchema
  • CakeSession
  • CakeSocket
  • ClassRegistry
  • Component
  • Configure
  • ConnectionManager
  • ConsoleShell
  • ContainableBehavior
  • Controller
  • ControllerTask
  • CookieComponent
  • DataSource
  • DbAcl
  • DbAclSchema
  • DbConfigTask
  • DboAdodb
  • DboDb2
  • DboFirebird
  • DboMssql
  • DboMysql
  • DboMysqlBase
  • DboMysqli
  • DboOdbc
  • DboOracle
  • DboPostgres
  • DboSource
  • DboSqlite
  • DboSybase
  • Debugger
  • EmailComponent
  • ErrorHandler
  • ExtractTask
  • File
  • FileEngine
  • Flay
  • Folder
  • FormHelper
  • Helper
  • HtmlHelper
  • HttpSocket
  • I18n
  • I18nModel
  • i18nSchema
  • I18nShell
  • Inflector
  • IniAcl
  • JavascriptHelper
  • JsHelper
  • JsHelperObject
  • L10n
  • MagicDb
  • MagicFileResource
  • MediaView
  • MemcacheEngine
  • Model
  • ModelBehavior
  • ModelTask
  • Multibyte
  • NumberHelper
  • Object
  • Overloadable
  • Overloadable2
  • PagesController
  • PaginatorHelper
  • Permission
  • PluginTask
  • ProjectTask
  • RequestHandlerComponent
  • Router
  • RssHelper
  • Sanitize
  • Scaffold
  • ScaffoldView
  • SchemaShell
  • Security
  • SecurityComponent
  • SessionComponent
  • SessionHelper
  • SessionsSchema
  • Set
  • Shell
  • String
  • TestSuiteShell
  • TestTask
  • TextHelper
  • ThemeView
  • TimeHelper
  • TranslateBehavior
  • TreeBehavior
  • Validation
  • View
  • ViewTask
  • XcacheEngine
  • Xml
  • XmlElement
  • XmlHelper
  • XmlManager
  • XmlNode
  • XmlTextNode

Functions

  • __enclose
  • make_clean_css
  • mb_encode_mimeheader
  • mb_stripos
  • mb_stristr
  • mb_strlen
  • mb_strpos
  • mb_strrchr
  • mb_strrichr
  • mb_strripos
  • mb_strrpos
  • mb_strstr
  • mb_strtolower
  • mb_strtoupper
  • mb_substr
  • mb_substr_count
  • write_css_cache
  1: <?php
  2: /* SVN FILE: $Id$ */
  3: /**
  4:  * Text Helper
  5:  *
  6:  * Text manipulations: Highlight, excerpt, truncate, strip of links, convert email addresses to mailto: links...
  7:  *
  8:  * PHP versions 4 and 5
  9:  *
 10:  * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 11:  * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 12:  *
 13:  * Licensed under The MIT License
 14:  * Redistributions of files must retain the above copyright notice.
 15:  *
 16:  * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 17:  * @link          http://cakephp.org CakePHP(tm) Project
 18:  * @package       cake
 19:  * @subpackage    cake.cake.libs.view.helpers
 20:  * @since         CakePHP(tm) v 0.10.0.1076
 21:  * @version       $Revision$
 22:  * @modifiedby    $LastChangedBy$
 23:  * @lastmodified  $Date$
 24:  * @license       http://www.opensource.org/licenses/mit-license.php The MIT License
 25:  */
 26: /**
 27:  * Included libraries.
 28:  *
 29:  */
 30: if (!class_exists('HtmlHelper')) {
 31:     App::import('Helper', 'Html');
 32: }
 33: if (!class_exists('Multibyte')) {
 34:     App::import('Core', 'Multibyte');
 35: }
 36: /**
 37:  * Text helper library.
 38:  *
 39:  * Text manipulations: Highlight, excerpt, truncate, strip of links, convert email addresses to mailto: links...
 40:  *
 41:  * @package       cake
 42:  * @subpackage    cake.cake.libs.view.helpers
 43:  */
 44: class TextHelper extends AppHelper {
 45: /**
 46:  * Highlights a given phrase in a text. You can specify any expression in highlighter that
 47:  * may include the \1 expression to include the $phrase found.
 48:  *
 49:  * @param string $text Text to search the phrase in
 50:  * @param string $phrase The phrase that will be searched
 51:  * @param string $highlighter The piece of html with that the phrase will be highlighted
 52:  * @param boolean $considerHtml If true, will ignore any HTML tags, ensuring that only the correct text is highlighted
 53:  * @return string The highlighted text
 54:  * @access public
 55:  */
 56:     function highlight($text, $phrase, $highlighter = '<span class="highlight">\1</span>', $considerHtml = false) {
 57:         if (empty($phrase)) {
 58:             return $text;
 59:         }
 60: 
 61:         if (is_array($phrase)) {
 62:             $replace = array();
 63:             $with = array();
 64: 
 65:             foreach ($phrase as $key => $value) {
 66:                 $key = $value;
 67:                 $value = $highlighter;
 68:                 $key = '(' . preg_quote($key, '|') . ')';
 69:                 if ($considerHtml) {
 70:                     $key = '(?![^<]+>)' . $key . '(?![^<]+>)';
 71:                 }
 72:                 $replace[] = '|' . $key . '|iu';
 73:                 $with[] = empty($value) ? $highlighter : $value;
 74:             }
 75:             return preg_replace($replace, $with, $text);
 76:         } else {
 77:             $phrase = '(' . preg_quote($phrase, '|') . ')';
 78:             if ($considerHtml) {
 79:                 $phrase = '(?![^<]+>)' . $phrase . '(?![^<]+>)';
 80:             }
 81:             return preg_replace('|'.$phrase.'|iu', $highlighter, $text);
 82:         }
 83:     }
 84: /**
 85:  * Strips given text of all links (<a href=....)
 86:  *
 87:  * @param string $text Text
 88:  * @return string The text without links
 89:  * @access public
 90:  */
 91:     function stripLinks($text) {
 92:         return preg_replace('|<a\s+[^>]+>|im', '', preg_replace('|<\/a>|im', '', $text));
 93:     }
 94: /**
 95:  * Adds links (<a href=....) to a given text, by finding text that begins with
 96:  * strings like http:// and ftp://.
 97:  *
 98:  * @param string $text Text to add links to
 99:  * @param array $htmlOptions Array of HTML options.
100:  * @return string The text with links
101:  * @access public
102:  */
103:     function autoLinkUrls($text, $htmlOptions = array()) {
104:         $options = var_export($htmlOptions, true);
105:         $text = preg_replace_callback('#(?<!href="|">)((?:https?|ftp|nntp)://[^\s<>()]+)#i', create_function('$matches',
106:             '$Html = new HtmlHelper(); $Html->tags = $Html->loadConfig(); return $Html->link($matches[0], $matches[0],' . $options . ');'), $text);
107: 
108:         return preg_replace_callback('#(?<!href="|">)(?<!http://|https://|ftp://|nntp://)(www\.[^\n\%\ <]+[^<\n\%\,\.\ <])(?<!\))#i',
109:             create_function('$matches', '$Html = new HtmlHelper(); $Html->tags = $Html->loadConfig(); return $Html->link($matches[0], "http://" . $matches[0],' . $options . ');'), $text);
110:     }
111: /**
112:  * Adds email links (<a href="mailto:....) to a given text.
113:  *
114:  * @param string $text Text
115:  * @param array $htmlOptions Array of HTML options.
116:  * @return string The text with links
117:  * @access public
118:  */
119:     function autoLinkEmails($text, $htmlOptions = array()) {
120:         $options = 'array(';
121: 
122:         foreach ($htmlOptions as $option => $value) {
123:             $options .= "'$option' => '$value', ";
124:         }
125:         $options .= ')';
126:         $atom = '[a-z0-9!#$%&\'*+\/=?^_`{|}~-]';
127: 
128:         return preg_replace_callback('/(' . $atom . '+(?:\.' . $atom . '+)*@[a-z0-9-]+(?:\.[a-z0-9-]+)+)/i',
129:                         create_function('$matches', '$Html = new HtmlHelper(); $Html->tags = $Html->loadConfig(); return $Html->link($matches[0], "mailto:" . $matches[0],' . $options . ');'), $text);
130:     }
131: /**
132:  * Convert all links and email adresses to HTML links.
133:  *
134:  * @param string $text Text
135:  * @param array $htmlOptions Array of HTML options.
136:  * @return string The text with links
137:  * @access public
138:  */
139:     function autoLink($text, $htmlOptions = array()) {
140:         return $this->autoLinkEmails($this->autoLinkUrls($text, $htmlOptions), $htmlOptions);
141:     }
142: /**
143:  * Truncates text.
144:  *
145:  * Cuts a string to the length of $length and replaces the last characters
146:  * with the ending if the text is longer than length.
147:  *
148:  * @param string  $text String to truncate.
149:  * @param integer $length Length of returned string, including ellipsis.
150:  * @param mixed $ending If string, will be used as Ending and appended to the trimmed string. Can also be an associative array that can contain the last three params of this method.
151:  * @param boolean $exact If false, $text will not be cut mid-word
152:  * @param boolean $considerHtml If true, HTML tags would be handled correctly
153:  * @return string Trimmed string.
154:  */
155:     function truncate($text, $length = 100, $ending = '...', $exact = true, $considerHtml = false) {
156:         if (is_array($ending)) {
157:             extract($ending);
158:         }
159:         if ($considerHtml) {
160:             if (mb_strlen(preg_replace('/<.*?>/', '', $text)) <= $length) {
161:                 return $text;
162:             }
163:             $totalLength = mb_strlen(strip_tags($ending));
164:             $openTags = array();
165:             $truncate = '';
166:             preg_match_all('/(<\/?([\w+]+)[^>]*>)?([^<>]*)/', $text, $tags, PREG_SET_ORDER);
167:             foreach ($tags as $tag) {
168:                 if (!preg_match('/img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param/s', $tag[2])) {
169:                     if (preg_match('/<[\w]+[^>]*>/s', $tag[0])) {
170:                         array_unshift($openTags, $tag[2]);
171:                     } else if (preg_match('/<\/([\w]+)[^>]*>/s', $tag[0], $closeTag)) {
172:                         $pos = array_search($closeTag[1], $openTags);
173:                         if ($pos !== false) {
174:                             array_splice($openTags, $pos, 1);
175:                         }
176:                     }
177:                 }
178:                 $truncate .= $tag[1];
179: 
180:                 $contentLength = mb_strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $tag[3]));
181:                 if ($contentLength + $totalLength > $length) {
182:                     $left = $length - $totalLength;
183:                     $entitiesLength = 0;
184:                     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)) {
185:                         foreach ($entities[0] as $entity) {
186:                             if ($entity[1] + 1 - $entitiesLength <= $left) {
187:                                 $left--;
188:                                 $entitiesLength += mb_strlen($entity[0]);
189:                             } else {
190:                                 break;
191:                             }
192:                         }
193:                     }
194: 
195:                     $truncate .= mb_substr($tag[3], 0 , $left + $entitiesLength);
196:                     break;
197:                 } else {
198:                     $truncate .= $tag[3];
199:                     $totalLength += $contentLength;
200:                 }
201:                 if ($totalLength >= $length) {
202:                     break;
203:                 }
204:             }
205:         } else {
206:             if (mb_strlen($text) <= $length) {
207:                 return $text;
208:             } else {
209:                 $truncate = mb_substr($text, 0, $length - strlen($ending));
210:             }
211:         }
212:         if (!$exact) {
213:             $spacepos = mb_strrpos($truncate, ' ');
214:             if (isset($spacepos)) {
215:                 if ($considerHtml) {
216:                     $bits = mb_substr($truncate, $spacepos);
217:                     preg_match_all('/<\/([a-z]+)>/', $bits, $droppedTags, PREG_SET_ORDER);
218:                     if (!empty($droppedTags)) {
219:                         foreach ($droppedTags as $closingTag) {
220:                             if (!in_array($closingTag[1], $openTags)) {
221:                                 array_unshift($openTags, $closingTag[1]);
222:                             }
223:                         }
224:                     }
225:                 }
226:                 $truncate = mb_substr($truncate, 0, $spacepos);
227:             }
228:         }
229: 
230:         $truncate .= $ending;
231: 
232:         if ($considerHtml) {
233:             foreach ($openTags as $tag) {
234:                 $truncate .= '</'.$tag.'>';
235:             }
236:         }
237: 
238:         return $truncate;
239:     }
240: /**
241:  * Alias for truncate().
242:  *
243:  * @see TextHelper::truncate()
244:  * @access public
245:  */
246:     function trim() {
247:         $args = func_get_args();
248:         return call_user_func_array(array(&$this, 'truncate'), $args);
249:     }
250: /**
251:  * Extracts an excerpt from the text surrounding the phrase with a number of characters on each side determined by radius.
252:  *
253:  * @param string $text String to search the phrase in
254:  * @param string $phrase Phrase that will be searched for
255:  * @param integer $radius The amount of characters that will be returned on each side of the founded phrase
256:  * @param string $ending Ending that will be appended
257:  * @return string Modified string
258:  * @access public
259:  */
260:     function excerpt($text, $phrase, $radius = 100, $ending = "...") {
261:         if (empty($text) or empty($phrase)) {
262:             return $this->truncate($text, $radius * 2, $ending);
263:         }
264: 
265:         $phraseLen = strlen($phrase);
266:         if ($radius < $phraseLen) {
267:             $radius = $phraseLen;
268:         }
269: 
270:         $pos = strpos(strtolower($text), strtolower($phrase));
271: 
272:         $startPos = 0;
273:         if ($pos > $radius) {
274:             $startPos = $pos - $radius;
275:         }
276: 
277:         $textLen = strlen($text);
278: 
279:         $endPos = $pos + $phraseLen + $radius;
280:         if ($endPos >= $textLen) {
281:             $endPos = $textLen;
282:         }
283: 
284:         $excerpt = substr($text, $startPos, $endPos - $startPos);
285:         if ($startPos != 0) {
286:             $excerpt = substr_replace($excerpt, $ending, 0, $phraseLen);
287:         }
288: 
289:         if ($endPos != $textLen) {
290:             $excerpt = substr_replace($excerpt, $ending, -$phraseLen);
291:         }
292: 
293:         return $excerpt;
294:     }
295: /**
296:  * Creates a comma separated list where the last two items are joined with 'and', forming natural English
297:  *
298:  * @param array $list The list to be joined
299:  * @return string
300:  * @access public
301:  */
302:     function toList($list, $and = 'and') {
303:         $return = '';
304:         $count = count($list) - 1;
305:         $counter = 0;
306:         foreach ($list as $i => $item) {
307:             $return .= $item;
308:             if ($count > 0 && $counter < $count) {
309:                 $return .= ($counter < $count - 1 ? ', ' : " {$and} ");
310:             }
311:             $counter++;
312:         }
313:         return $return;
314:     }
315: /**
316:  * Text-to-html parser, similar to Textile or RedCloth, only with a little different syntax.
317:  *
318:  * @param string $text String to "flay"
319:  * @param boolean $allowHtml Set to true if if html is allowed
320:  * @return string "Flayed" text
321:  * @access public
322:  * @todo Change this. We need a real Textile parser.
323:  * @codeCoverageIgnoreStart
324:  */
325:     function flay($text, $allowHtml = false) {
326:         trigger_error(__('(TextHelper::flay) Deprecated: the Flay library is no longer supported and will be removed in a future version.', true), E_USER_WARNING);
327:         if (!class_exists('Flay')) {
328:             uses('flay');
329:         }
330:         return Flay::toHtml($text, false, $allowHtml);
331:     }
332: /**
333:  * @codeCoverageIgnoreEnd
334:  */
335: }
336: ?>
337: 
OpenHub
Rackspace
Rackspace
  • Business Solutions
  • Showcase
  • Documentation
  • Book
  • API
  • Videos
  • Reporting Security Issues
  • Privacy Policy
  • Logos & Trademarks
  • Community
  • Get Involved
  • Issues (GitHub)
  • Bakery
  • Featured Resources
  • Training
  • Meetups
  • My CakePHP
  • CakeFest
  • Newsletter
  • Linkedin
  • YouTube
  • Facebook
  • Twitter
  • Mastodon
  • Help & Support
  • Forum
  • Stack Overflow
  • Slack
  • Paid Support

Generated using CakePHP API Docs