Marcel Ang Marcel Ang - 2 months ago 22
PHP Question

PHP cut a paragraph

I have a paragraph :


Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.


I want to show only 140 character (I emboldened the 140 character above). So I use
substr()
function in PHP:

echo substr($str, 0, 140); // let say $str contain the paragraph above


As you can see above in the text, It cut the "minim" word into "mini" !!, if that's an English word, let say "Singular", and it suddenly cut info "Sing", it will have a different meaning and will make the entire sentence nonsense.

So I decide to cut the last sentence and there would not be any weird word resulting from the
substr()
function.

Anybody know how to cut the last sentences after
substr()
?

Answer

There are a few approaches to this, I suppose. The easiest one that comes to mind is exploding the string in words, removing the last one, and then imploding them again, as follows:

$str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.";
if (strlen($str) > 140)
{
    $str = substr($str, 0, 140);
    $str = explode(' ', $str);
    array_pop($str); // remove last word from array
    $str = implode(' ', $str);
}

So this should result in:

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad

You can also include ... to the string to give a sense of continuity with:

$str = $str . ' ...';