Cool Hand Luke UK Cool Hand Luke UK - 7 months ago 50
PHP Question

Making sure PHP substr finishes on a word not a character

I know how to use the substr function but this will happy end a string halfway through a word. I want the string to end at the end of a word how would I go about doing this? Would it involve regular expression? Any help very much appreciated.

This is what I have so far. Just the SubStr...

echo substr("$body",0,260);



It could be done with a regex, something like this will get up to 260 characters from the start of string up to a word boundary:

if (preg_match('/^.{1,260}\b/s', $body, $match))

Alternatively, you could maybe use the wordwrap function to break your $body into lines, then just extract the first line.