I’m trying to truncate a description field in PHP, and insert an ellipsis in a proper position, so the user can click and learn more.
So I retrieve some characters from a field:
LEFT(html,340) as descr
Then set the variable…
$desc= $a['descr'];
Now comes the hard part… I want to find last punctuation marks in the sting, and then replace them with ‘…’ because I believe it would be quite ugly to break a sentence in a random position. Then if the sentence is too long and without punctuation or if the outcome becomes too short, I would actually start replacing the first found space from the end.
$desc1=preg_replace('/([\.\-_,:].*)$/','...',$desc);
$desc=strlen(strlen($desc1)>170&&340>strlen($desc1))?$descr1:
preg_replace('/(\s.*)$/','...',substr($desc,0,300));
This is what I tried so far, the problem though is that it breaks the string at completely random position, but not from the position of the last punctuation mark. hmmm
Also it is powerless when couple of punctuation marks are found together.
Finally I would want to replace dashes only if they’re preceded by a space.
But I can’t seem to figure out how to do these things, I mean how to put it all together…
I’ll be glad if you could advice something on any of the above points.
Aight, that’s how I solved it
$desc1 = preg_replace('/[.,!:_]+[^.,!:_]*$/', '... ', $desc);
$desc=(strlen($desc1)<170)?preg_replace('/[\s]+[^\s]*$/', '... ', $desc) : $desc1;
Here’s my solution:
This outputs: