Cut A String To A Specified Length With PHP

Thursday, April 17, 2008 - 09:54

Cutting a string to a specified length is accomplished with the substr() function. For example, the following string variable, which we will cut to a maximum of 30 characters.

$string = 'This string is too long and will be cut short.';

The substr() function has three parameters. The first is the string, the second is where to start cutting from and the third is the amount of characters to cut to. So to cut to 30 characters we would use the following.

$string = substr($string,0,30);

The string variable is now set to the following.

$string = 'This string is too long and wi';

This example highlights the major problem with this function in that it will take no notice of the words in a string. The solution is to create a new function that will avoid cutting words apart when cutting a string by a number of characters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function substrwords($text, $maxchar, $end='...') {
    if (strlen($text) > $maxchar || $text == '') {
        $words = preg_split('/\s/', $text);      
        $output = '';
        $i      = 0;
        while (1) {
            $length = strlen($output)+strlen($words[$i]);
            if ($length > $maxchar) {
                break;
            } 
            else {
                $output .= " " . $words[$i];
                ++$i;
            }
        }
        $output .= $end;
    } 
    else {
        $output = $text;
    }
    return $output;
}

This function splits the string into words and then joins them back together again one by one. The good thing is that if there is a word that would make the string longer than the required number of characters it doesn't include the word. The function can be called like this.

echo substrwords($string,30);

This produces the following output.

This string is too long and...
Category: 
philipnorton42's picture

Philip Norton

Phil is the founder and administrator of #! code and is an IT professional working in the North West of the UK.
Google+ | Twitter

Comments

Great! Really useful! I was looking for that!
Hah! Exactly what I was looking for, thanks a bunch..! ;) By the way: this thing is rating pretty high on Google's search results; keep up the good work!

Save a bit of processor time by doing this:

1
2
3
4
5
6
$length = 0;
while ($length < $maxchar) {
$length += strlen($words[$i]);
   $output .= " " . $words[$i];
   ++$i;
}

Really work wonderfully gooooooooooood!!! you are a guru philip

Still works after all these years. Thanks for the helpful tip!

Something like this?

function truncate_text($body, $max_length) {
if (strlen($body) > $max_length) {
return substr($body, 0, strrpos(substr($body, 0, $max_length + 1), ' ')) . '...';
}
return $body;
}

People could also look at php's wordwrap function.

Add new comment