Categories
PHP

Truncate text to a specific length

In this code snippet, we’ll cut long strings short without truncating the text midword.

We’ll use substr and strrpos functions. substr function returns the portion of the string specified by the start and length parameters and strrpos funciton finds the position of the last occurrence of a substring in a string.

Truncate text with substr and strrpos functions

<?php
 $text = 'it is a very lenghty text';
 $maxChar = 10;
 $newText = substr($text,0,$maxChar);
 echo $newText;

The above code will return it is a ve with broken very ve word. To solve this problem we’ll find the position of the last space in the text.

$position = strrpos($truncated, ' ');

Now we know the position of the last space, we’ll truncate our text again with substr to this position to get rid of the broken word.

$truncated = substr($text, 0, $position);

The above code will return it is a.

Complete code of truncateText function:

We’ll create a function that takes a string variable containing text to truncate, and the maximum number of characters to allow in the new string:

<?php
 function truncateText($text, $maxChar){
    //Add extra space at the end of string
    $text = $text . ' ';

    //Use substr function
    $truncated = substr($text, 0, $maxChar);

    //Last space position
    $position = strrpos($truncated, ' ');

    //substr to whitespace pos
    $truncated = substr($text, 0, $position);

    return $truncated;
 }

Now use the truncateText function to truncate the text:

$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.
         Morbi sed massa convallis arcu vulputate sollicitudin.';
$trunText = truncateText($text,24);
echo $trunText;
//Prints: Lorem ipsum dolor sit

Manipulating substrings: