Text Helper

The Text Helper file contains functions that assist in working with Text.

Loading this Helper

This helper is loaded using the following code:

  1. helper('text');

Available Functions

The following functions are available:

  • randomstring([$type = 'alnum'[, $len = 8_]])

Parameters:

  • $type (string) – Randomization type
  • $len (int) – Output string lengthReturns:A random stringReturn type:string

Generates a random string based on the type and length you specify.Useful for creating passwords or generating random hashes.

The first parameter specifies the type of string, the second parameterspecifies the length. The following choices are available:

  • alpha: A string with lower and uppercase letters only.
  • alnum: Alphanumeric string with lower and uppercase characters.
  • basic: A random number based on mt_rand() (length ignored).
  • numeric: Numeric string.
  • nozero: Numeric string with no zeros.
  • md5: An encrypted random number based on md5() (fixed length of 32).
  • sha1: An encrypted random number based on sha1() (fixed length of 40).
  • crypto: A random string based on random_bytes().Usage example:
  1. echo random_string('alnum', 16);
  • incrementstring($str[, $separator = ''[, $first = 1]])

Parameters:

  • $str (string) – Input string
  • $separator (string) – Separator to append a duplicate number with
  • $first (int) – Starting numberReturns:An incremented stringReturn type:string

Increments a string by appending a number to it or increasing thenumber. Useful for creating “copies” or a file or duplicating databasecontent which has unique titles or slugs.

Usage example:

  1. echo increment_string('file', '_'); // "file_1"
  2. echo increment_string('file', '-', 2); // "file-2"
  3. echo increment_string('file_4'); // "file_5"
  • alternator($args)

Parameters:

  • $args (mixed) – A variable number of argumentsReturns:Alternated string(s)Return type:mixed

Allows two or more items to be alternated between, when cycling througha loop. Example:

  1. for ($i = 0; $i < 10; $i++)
  2. {
  3. echo alternator('string one', 'string two');
  4. }

You can add as many parameters as you want, and with each iteration ofyour loop the next item will be returned.

  1. for ($i = 0; $i < 10; $i++)
  2. {
  3. echo alternator('one', 'two', 'three', 'four', 'five');
  4. }

Note

To use multiple separate calls to this function simply call thefunction with no arguments to re-initialize.

  • reducedouble_slashes($str_)

Parameters:

  • $str (string) – Input stringReturns:A string with normalized slashesReturn type:string

Converts double slashes in a string to a single slash, except thosefound in URL protocol prefixes (e.g. http://).

Example:

  1. $string = "http://example.com//index.php";
  2. echo reduce_double_slashes($string); // results in "http://example.com/index.php"
  • stripslashes($data_)

Parameters:

  • $data (mixed) – Input string or an array of stringsReturns:String(s) with stripped slashesReturn type:mixed

Removes any slashes from an array of strings.

Example:

  1. $str = [
  2. 'question' => 'Is your name O\'reilly?',
  3. 'answer' => 'No, my name is O\'connor.'
  4. ];
  5.  
  6. $str = strip_slashes($str);

The above will return the following array:

  1. [
  2. 'question' => "Is your name O'reilly?",
  3. 'answer' => "No, my name is O'connor."
  4. ];

Note

For historical reasons, this function will also acceptand handle string inputs. This however makes it just analias for stripslashes().

  • reducemultiples($str[, $character = ''[, $trim = FALSE_]])

Parameters:

  • $str (string) – Text to search in
  • $character (string) – Character to reduce
  • $trim (bool) – Whether to also trim the specified characterReturns:Reduced stringReturn type:string

Reduces multiple instances of a particular character occurring directlyafter each other. Example:

  1. $string = "Fred, Bill,, Joe, Jimmy";
  2. $string = reduce_multiples($string,","); //results in "Fred, Bill, Joe, Jimmy"

If the third parameter is set to TRUE it will remove occurrences of thecharacter at the beginning and the end of the string. Example:

  1. $string = ",Fred, Bill,, Joe, Jimmy,";
  2. $string = reduce_multiples($string, ", ", TRUE); //results in "Fred, Bill, Joe, Jimmy"
  • quotesto_entities($str_)

Parameters:

  • $str (string) – Input stringReturns:String with quotes converted to HTML entitiesReturn type:string

Converts single and double quotes in a string to the corresponding HTMLentities. Example:

  1. $string = "Joe's \"dinner\"";
  2. $string = quotes_to_entities($string); //results in "Joe&#39;s &quot;dinner&quot;"
  • stripquotes($str_)

Parameters:

  • $str (string) – Input stringReturns:String with quotes strippedReturn type:string

Removes single and double quotes from a string. Example:

  1. $string = "Joe's \"dinner\"";
  2. $string = strip_quotes($string); //results in "Joes dinner"
  • wordlimiter($str[, $limit = 100[, $endchar = '…']])

Parameters:

  • $str (string) – Input string
  • $limit (int) – Limit
  • $end_char (string) – End character (usually an ellipsis)Returns:Word-limited stringReturn type:string

Truncates a string to the number of words specified. Example:

  1. $string = "Here is a nice text string consisting of eleven words.";
  2. $string = word_limiter($string, 4);
  3. // Returns: Here is a nice

The third parameter is an optional suffix added to the string. Bydefault it adds an ellipsis.

  • characterlimiter($str[, $n = 500[, $endchar = '…']])

Parameters:

  • $str (string) – Input string
  • $n (int) – Number of characters
  • $end_char (string) – End character (usually an ellipsis)Returns:Character-limited stringReturn type:string

Truncates a string to the number of characters specified. Itmaintains the integrity of words so the character count may be slightlymore or less than what you specify.

Example:

  1. $string = "Here is a nice text string consisting of eleven words.";
  2. $string = character_limiter($string, 20);
  3. // Returns: Here is a nice text string

The third parameter is an optional suffix added to the string, ifundeclared this helper uses an ellipsis.

Note

If you need to truncate to an exact number of characters, pleasesee the ellipsize() function below.

  • asciito_entities($str_)

Parameters:

  • $str (string) – Input stringReturns:A string with ASCII values converted to entitiesReturn type:string

Converts ASCII values to character entities, including high ASCII and MSWord characters that can cause problems when used in a web page, so thatthey can be shown consistently regardless of browser settings or storedreliably in a database. There is some dependence on your server’ssupported character sets, so it may not be 100% reliable in all cases,but for the most part, it should correctly identify characters outsidethe normal range (like accented characters).

Example:

  1. $string = ascii_to_entities($string);
  • entitiesto_ascii($str[, $all = TRUE_])

Parameters:

  • $str (string) – Input string
  • $all (bool) – Whether to convert unsafe entities as wellReturns:A string with HTML entities converted to ASCII charactersReturn type:string

This function does the opposite of ascii_to_entities().It turns character entities back into ASCII.

  • convertaccented_characters($str_)

Parameters:

  • $str (string) – Input stringReturns:A string with accented characters convertedReturn type:string

Transliterates high ASCII characters to low ASCII equivalents. Usefulwhen non-English characters need to be used where only standard ASCIIcharacters are safely used, for instance, in URLs.

Example:

  1. $string = convert_accented_characters($string);

Note

This function uses a companion config fileapp/Config/ForeignCharacters.php to define the to andfrom array for transliteration.

  • wordcensor($str, $censored[, $replacement = ''_])

Parameters:

  • $str (string) – Input string
  • $censored (array) – List of bad words to censor
  • $replacement (string) – What to replace bad words withReturns:Censored stringReturn type:string

Enables you to censor words within a text string. The first parameterwill contain the original string. The second will contain an array ofwords which you disallow. The third (optional) parameter can containa replacement value for the words. If not specified they are replacedwith pound signs: ####.

Example:

  1. $disallowed = ['darn', 'shucks', 'golly', 'phooey'];
  2. $string = word_censor($string, $disallowed, 'Beep!');
  • highlightcode($str_)

Parameters:

  • $str (string) – Input stringReturns:String with code highlighted via HTMLReturn type:string

Colorizes a string of code (PHP, HTML, etc.). Example:

  1. $string = highlight_code($string);

The function uses PHP’s highlight_string() function, so thecolors used are the ones specified in your php.ini file.

  • highlightphrase($str, $phrase[, $tagopen = ''[, $tag_close = '']])

Parameters:

  • $str (string) – Input string
  • $phrase (string) – Phrase to highlight
  • $tag_open (string) – Opening tag used for the highlight
  • $tag_close (string) – Closing tag for the highlightReturns:String with a phrase highlighted via HTMLReturn type:string

Will highlight a phrase within a text string. The first parameter willcontain the original string, the second will contain the phrase you wishto highlight. The third and fourth parameters will contain theopening/closing HTML tags you would like the phrase wrapped in.

Example:

  1. $string = "Here is a nice text string about nothing in particular.";
  2. echo highlight_phrase($string, "nice text", '<span style="color:#990000;">', '</span>');

The above code prints:

  1. Here is a <span style="color:#990000;">nice text</span> string about nothing in particular.

Note

This function used to use the <strong> tag by default. Older browsersmight not support the new HTML5 mark tag, so it is recommended that youinsert the following CSS code into your stylesheet if you need to supportsuch browsers:

  1. mark {
  2. background: #ff0;
  3. color: #000;
  4. };
  • wordwrap($str[, $charlim = 76_])

Parameters:

  • $str (string) – Input string
  • $charlim (int) – Character limitReturns:Word-wrapped stringReturn type:string

Wraps text at the specified character count while maintainingcomplete words.

Example:

  1. $string = "Here is a simple string of text that will help us demonstrate this function.";
  2. echo word_wrap($string, 25);
  3.  
  4. // Would produce:
  5. // Here is a simple string
  6. // of text that will help us
  7. // demonstrate this
  8. // function.

Excessively long words will be split, but URLs will not be.

  • ellipsize($str, $max_length[, $position = 1[, $ellipsis = '…']])

Parameters:

  • $str (string) – Input string
  • $max_length (int) – String length limit
  • $position (mixed) – Position to split at (int or float)
  • $ellipsis (string) – What to use as the ellipsis characterReturns:Ellipsized stringReturn type:string

This function will strip tags from a string, split it at a definedmaximum length, and insert an ellipsis.

The first parameter is the string to ellipsize, the second is the numberof characters in the final string. The third parameter is where in thestring the ellipsis should appear from 0 - 1, left to right. Forexample. a value of 1 will place the ellipsis at the right of thestring, .5 in the middle, and 0 at the left.

An optional fourth parameter is the kind of ellipsis. By default,… will be inserted.

Example:

  1. $str = 'this_string_is_entirely_too_long_and_might_break_my_design.jpg';
  2. echo ellipsize($str, 32, .5);

Produces:

  1. this_string_is_e&hellip;ak_my_design.jpg
  • excerpt($text, $phrase = false, $radius = 100, $ellipsis = '…')

Parameters:

  • $text (string) – Text to extract an excerpt
  • $phrase (string) – Phrase or word to extract the text arround
  • $radius (int) – Number of characters before and after $phrase
  • $ellipsis (string) – What to use as the ellipsis characterReturns:Excerpt.Return type:string

This function will extract $radius number of characters before and after thecentral $phrase with an elipsis before and after.

The first paramenter is the text to extract an excerpt from, the second is thecentral word or phrase to count before and after. The third parameter is thenumber of characters to count before and after the central phrase. If no phrasepassed, the excerpt will include the first $radius characters with the elipsisat the end.

Example:

  1. $text = 'Ut vel faucibus odio. Quisque quis congue libero. Etiam gravida
  2. eros lorem, eget porttitor augue dignissim tincidunt. In eget risus eget
  3. mauris faucibus molestie vitae ultricies odio. Vestibulum id ultricies diam.
  4. Curabitur non mauris lectus. Phasellus eu sodales sem. Integer dictum purus
  5. ac enim hendrerit gravida. Donec ac magna vel nunc tincidunt molestie sed
  6. vitae nisl. Cras sed auctor mauris, non dictum tortor. Nulla vel scelerisque
  7. arcu. Cras ac ipsum sit amet augue laoreet laoreet. Aenean a risus lacus.
  8. Sed ut tortor diam.';
  9.  
  10. echo excerpt($str, 'Donec');

Produces:

  1. ... non mauris lectus. Phasellus eu sodales sem. Integer dictum purus ac
  2. enim hendrerit gravida. Donec ac magna vel nunc tincidunt molestie sed
  3. vitae nisl. Cras sed auctor mauris, non dictum ...