Text

  • class Cake\Utility\Text
  • The Text class includes convenience methods for creating and manipulatingstrings and is normally accessed statically. Example:Text::uuid().

If you need Cake\View\Helper\TextHelper functionalities outsideof a View, use the Text class:

  1. namespace App\Controller;
  2.  
  3. use Cake\Utility\Text;
  4.  
  5. class UsersController extends AppController
  6. {
  7. public function initialize()
  8. {
  9. parent::initialize();
  10. $this->loadComponent('Auth')
  11. };
  12.  
  13. public function afterLogin()
  14. {
  15. $message = $this->Users->find('new_message');
  16. if (!empty($message)) {
  17. // Notify user of new message
  18. $this->Flash->success(__(
  19. 'You have a new message: {0}',
  20. Text::truncate($message['Message']['body'], 255, ['html' => true])
  21. ));
  22. }
  23. }
  24. }

Convert Strings into ASCII

  • static Cake\Utility\Text::transliterate($string, $transliteratorId = null)
  • Transliterate by default converts all characters in provided string intoequivalent ASCII characters. The method expects UTF-8 encoding. The characterconversion can be controlled using transliteration identifiers which you canpass using the $transliteratorId argument or change the default identifierstring using Text::setTransliteratorId(). ICU transliteration identifiersare basically of form <source script>:<target script> and you can specifymultiple conversion pairs separated by ;. You can find more info abouttransliterator identifiershere:
  1. // apple puree
  2. Text::transliterate('apple purée');
  3.  
  4. // Ubermensch (only latin characters are transliterated)
  5. Text::transliterate('Übérmensch', 'Latin-ASCII;');

Creating URL Safe Strings

  • static Cake\Utility\Text::slug($string, $options = [])
  • Slug transliterates all characters into ASCII versions and converting unmatchedcharacters and spaces to dashes. The slug method expects UTF-8 encoding.

You can provide an array of options that controls slug. $options can also bea string in which case it will be used as replacement string. The supportedoptions are:

  • replacement Replacement string, defaults to ‘-‘.

  • transliteratorId A valid tranliterator id string. If default nullText::$_defaultTransliteratorId to be used.If false no transliteration will be done, only non words will be removed.

  • preserve Specific non-word character to preserve. Defaults to null.For e.g. this option can be set to ‘.’ to generate clean file names:

  1. // apple-puree
  2. Text::slug('apple purée');
  3.  
  4. // apple_puree
  5. Text::slug('apple purée', '_');
  6.  
  7. // foo-bar.tar.gz
  8. Text::slug('foo bar.tar.gz', ['preserve' => '.']);

Generating UUIDs

  • static Cake\Utility\Text::uuid
  • The UUID method is used to generate unique identifiers as per RFC 4122. TheUUID is a 128-bit string in the format of485fc381-e790-47a3-9794-1337c0a8fe68.
  1. Text::uuid(); // 485fc381-e790-47a3-9794-1337c0a8fe68

Simple String Parsing

  • static Cake\Utility\Text::tokenize($data, $separator = ', ', $leftBound = '(', $rightBound = ')')
  • Tokenizes a string using $separator, ignoring any instance of $separatorthat appears between $leftBound and $rightBound.

This method can be useful when splitting up data that has regular formattingsuch as tag lists:

  1. $data = "cakephp 'great framework' php";
  2. $result = Text::tokenize($data, ' ', "'", "'");
  3. // Result contains
  4. ['cakephp', "'great framework'", 'php'];
  • Cake\Utility\Text::parseFileSize(string $size, $default)
  • This method unformats a number from a human-readable byte size to an integernumber of bytes:
  1. $int = Text::parseFileSize('2GB');

Formatting Strings

  • static Cake\Utility\Text::insert($string, $data, $options = [])
  • The insert method is used to create string templates and to allow for key/valuereplacements:
  1. Text::insert(
  2. 'My name is :name and I am :age years old.',
  3. ['name' => 'Bob', 'age' => '65']
  4. );
  5. // Returns: "My name is Bob and I am 65 years old."
  • static Cake\Utility\Text::cleanInsert($string, $options = [])
  • Cleans up a Text::insert formatted string with given $options dependingon the ‘clean’ key in $options. The default method used is text but html isalso available. The goal of this function is to replace all whitespace andunneeded markup around placeholders that did not get replaced byText::insert.

You can use the following options in the options array:

  1. $options = [
  2. 'clean' => [
  3. 'method' => 'text', // or html
  4. ],
  5. 'before' => '',
  6. 'after' => ''
  7. ];

Wrapping Text

  • static Cake\Utility\Text::wrap($text, $options = [])
  • Wraps a block of text to a set width and indents blocks as well.Can intelligently wrap text so words are not sliced across lines:
  1. $text = 'This is the song that never ends.';
  2. $result = Text::wrap($text, 22);
  3.  
  4. // Returns
  5. This is the song that
  6. never ends.

You can provide an array of options that control how wrapping is done. Thesupported options are:

  • width The width to wrap to. Defaults to 72.
  • wordWrap Whether or not to wrap whole words. Defaults to true.
  • indent The character to indent lines with. Defaults to ‘’.
  • indentAt The line number to start indenting text. Defaults to 0.
  • static Cake\Utility\Text::wrapBlock($text, $options = [])
  • If you need to ensure that the total width of the generated block won’texceed a certain length even with internal identation, you need to usewrapBlock() instead of wrap(). This is particulary useful to generatetext for the console for example. It accepts the same options as wrap():
  1. $text = 'This is the song that never ends. This is the song that never ends.';
  2. $result = Text::wrapBlock($text, [
  3. 'width' => 22,
  4. 'indent' => ' → ',
  5. 'indentAt' => 1
  6. ]);
  7.  
  8. // Returns
  9. This is the song that
  10. never ends. This
  11. is the song that
  12. never ends.

Highlighting Substrings

  • Cake\Utility\Text::highlight(string $haystack, string $needle, array $options = [])
  • Highlights $needle in $haystack using the $options['format'] stringspecified or a default string.

Options:

  • format string - The piece of HTML with the phrase that will behighlighted
  • html bool - If true, will ignore any HTML tags, ensuring that onlythe correct text is highlighted
    Example:
  1. // Called as TextHelper
  2. echo $this->Text->highlight(
  3. $lastSentence,
  4. 'using',
  5. ['format' => '<span class="highlight">\1</span>']
  6. );
  7.  
  8. // Called as Text
  9. use Cake\Utility\Text;
  10.  
  11. echo Text::highlight(
  12. $lastSentence,
  13. 'using',
  14. ['format' => '<span class="highlight">\1</span>']
  15. );

Output:

  1. Highlights $needle in $haystack <span class="highlight">using</span> the
  2. $options['format'] string specified or a default string.
  • Cake\Utility\Text::stripLinks($text)
  • Strips the supplied $text of any HTML links.

Truncating Text

  • Cake\Utility\Text::truncate(string $text, int $length = 100, array $options)
  • If $text is longer than $length, this method truncates it at $lengthand adds a suffix consisting of 'ellipsis', if defined. If 'exact' ispassed as false, the truncation will occur at the first whitespace after thepoint at which $length is exceeded. If 'html' is passed as true,HTML tags will be respected and will not be cut off.

$options is used to pass all extra parameters, and has the followingpossible keys by default, all of which are optional:

  1. [
  2. 'ellipsis' => '...',
  3. 'exact' => true,
  4. 'html' => false
  5. ]

Example:

  1. // Called as TextHelper
  2. echo $this->Text->truncate(
  3. 'The killer crept forward and tripped on the rug.',
  4. 22,
  5. [
  6. 'ellipsis' => '...',
  7. 'exact' => false
  8. ]
  9. );
  10.  
  11. // Called as Text
  12. use Cake\Utility\Text;
  13.  
  14. echo Text::truncate(
  15. 'The killer crept forward and tripped on the rug.',
  16. 22,
  17. [
  18. 'ellipsis' => '...',
  19. 'exact' => false
  20. ]
  21. );

Output:

  1. The killer crept...

Truncating the Tail of a String

  • Cake\Utility\Text::tail(string $text, int $length = 100, array $options)
  • If $text is longer than $length, this method removes an initialsubstring with length consisting of the difference and prepends a prefixconsisting of 'ellipsis', if defined. If 'exact' is passed as false,the truncation will occur at the first whitespace prior to the point at whichtruncation would otherwise take place.

$options is used to pass all extra parameters, and has the followingpossible keys by default, all of which are optional:

  1. [
  2. 'ellipsis' => '...',
  3. 'exact' => true
  4. ]

Example:

  1. $sampleText = 'I packed my bag and in it I put a PSP, a PS3, a TV, ' .
  2. 'a C# program that can divide by zero, death metal t-shirts'
  3.  
  4. // Called as TextHelper
  5. echo $this->Text->tail(
  6. $sampleText,
  7. 70,
  8. [
  9. 'ellipsis' => '...',
  10. 'exact' => false
  11. ]
  12. );
  13.  
  14. // Called as Text
  15. use Cake\Utility\Text;
  16.  
  17. echo Text::tail(
  18. $sampleText,
  19. 70,
  20. [
  21. 'ellipsis' => '...',
  22. 'exact' => false
  23. ]
  24. );

Output:

  1. ...a TV, a C# program that can divide by zero, death metal t-shirts

Extracting an Excerpt

  • Cake\Utility\Text::excerpt(string $haystack, string $needle, integer $radius=100, string $ellipsis="…")
  • Extracts an excerpt from $haystack surrounding the $needle with a numberof characters on each side determined by $radius, and prefix/suffix with$ellipsis. This method is especially handy for search results. The querystring or keywords can be shown within the resulting document.
  1. // Called as TextHelper
  2. echo $this->Text->excerpt($lastParagraph, 'method', 50, '...');
  3.  
  4. // Called as Text
  5. use Cake\Utility\Text;
  6.  
  7. echo Text::excerpt($lastParagraph, 'method', 50, '...');

Output:

  1. ... by $radius, and prefix/suffix with $ellipsis. This method is especially
  2. handy for search results. The query...

Converting an Array to Sentence Form

  • Cake\Utility\Text::toList(array $list, $and='and', $separator=', ')
  • Creates a comma-separated list where the last two items are joined with ‘and’:
  1. $colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
  2.  
  3. // Called as TextHelper
  4. echo $this->Text->toList($colors);
  5.  
  6. // Called as Text
  7. use Cake\Utility\Text;
  8.  
  9. echo Text::toList($colors);

Output:

  1. red, orange, yellow, green, blue, indigo and violet