Skip to content
Advertisement

Truncate string to maximum length before space or dot to avoid breaking a word

I found the following PHP script create by webbiedave.

// strip tags to avoid breaking any html
$string = strip_tags($string);
if (strlen($string) > 500) {
    // truncate string
    $stringCut = substr($string, 0, 500);

    // make sure it ends in a word so assassinate doesn't become ass...
    $string = substr($stringCut, 0, strrpos($stringCut, ' ')).'... <a href="/this/story">Read More</a>';
}
echo $string;

Now my question is: How can I specify in strrpos() to search for space or dot?

So if I set a maximum string length of 22 and my inout string is:

StackOverFlow is the best site ever

Excluding the appended HTML tag, the output will be:

StackOverFlow is the...

If I have an input of:

http://stackoverflow.com is the best site ever

Excluding the appended HTML tag, the output will unfortunately be

...

How can I modify this script to cut text if it finds a dot in the string so that http://stackoverflow.com is the best site ever becomes http://stackoverflow ... ?

Advertisement

Answer

I would check string from end, cause You need to delete words that are incomplete. Condition of that incomplete word is when short string is not ending with space or with a end character such as ‘!’ or just dot. Next cond is to see if +1 sign after end of string is also such character. If it is the You just have to del any character from end to next space. This could be done by regexp (something similiar to /[:alfa]+$/, probadly better would have to be done).

This is a simple way to do basic things, but a good start I think.

EXAMPLE of what it could be:

function word_wrap_custom($string, $limit){
$oneWord = explode(' ', $string);
if(count($oneWord) < 2 )
    return $oneWord[0];
$string = substr($string, 0, $limit + 2);

$endchar =  substr($string, $limit, $limit + 1);

$postendchar = substr($string, $limit + 1, $limit + 2);

$arrAccetpEndChar = array(' ', '!', '?', ',', '.', ';', ':');

if(in_array($postendchar, $arrAccetpEndChar) || in_array($endchar, $arrAccetpEndChar))
{
    return $string;
}
else
{
    return preg_replace('/[A-Za-z0-9]+$/', '', $string);
}
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement