PHP cut the paragraph

I have a paragraph:

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tem incididunt ut labore et dolore magna aliqua. Ut en ad ad mini m veniam, quis nostrud, carrying out work performed in accordance with the requirements set forth in it.

I want to show only 140 characters (I encouraged 140 characters above). Therefore, I use a function substr()in PHP:

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

As you can see above in the text, he cut the word “minim” into “mini” !! if it is an English word, say, “Singular” and it suddenly breaks the information “Sing”, it will have a different meaning and will make the whole phrase meaningless .

So, I decided to cut out the last sentence, and there would not be any strange word as a result of the function substr().

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

+4
source share
1 answer

There are several approaches to this, I suppose. The easiest one that comes to mind is the explosion of a line in words, the removal of the line, and then its subsequent untying 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);
}

Thus, this should result in:

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

You can also include ...in a line to give a sense of continuity:

$str = $str . ' ...';
+4
source

All Articles