Cut A String To A Specified Length With PHP

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.

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.

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...

 

Comments

Great! Really useful! I was looking for that!
Permalink
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!
Permalink
Its useful. thanks so much.
Permalink

Save a bit of processor time by doing this:

$length = 0;
while ($length  $maxchar) {
$length += strlen($words[$i]);
   $output .= " " . $words[$i];
   ++$i;
}
Permalink
Good. very Useful though It gives error when the string is empty.
Permalink
Really work wonderfully gooooooooooood!!! you are a guru philip
Permalink
Still works after all these years. Thanks for the helpful tip!
Permalink
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.
Permalink
Great!! It was extremely helpful. This was so easy to follow and exactly what I was looking for. Thanks.
Permalink

Thanks for this, it saved my skin

Permalink

Great.! - Still working, tested with PHP7.2

// UTF8 compatibility » add "mb_" before "strlen" for UTF8 compatibility

function substrwords($text, $maxchar, $end=' ...') {

    if (mb_strlen($text) > $maxchar || $text == '') {

        $words = preg_split('/\s/', $text);      

        $output = '';

        $i      = 0;

        while (1) {

            $length = mb_strlen($output)+mb_strlen($words[$i]);

            if ($length > $maxchar) {

                break;

            } 

            else {

                $output .= " " . $words[$i];

                ++$i;

            }

        }

        $output .= $end;

    } 

    else {

        $output = $text;

    }

    return $output;

}

 

Permalink

(Y)

Permalink

This is so coolaborative, then I show an more easy way:

    function substrwords($text, $maxchar) {
        $output = "";
        $output .= substr($text, 0, $maxchar);
        $output .= " ...";
        return $output;
    }

 

Maybe can validate if $text containt a string, but that is correspondence.

If a call a function is better make a condition first, like that:

if(empty($_POST['string_value_container'])) {

   /* Or the process that you consider necessary, or not the process then use ! to go on else directly */

   echo "Not contain an valid char/string"

}

else {

   echo substrwords($string,30);

}

 

Permalink

Thx for this little handy function.

Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
2 + 2 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.