tags:

views:

1060

answers:

4

Hi

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);

Cheers

+3  A: 

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:

$line=$body;
if (preg_match('/^.{1,260}\b/s', $body, $match))
{
    $line=$match[0];
}

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

Paul Dixon
a downvote! someone out there hates regular expressions!
Paul Dixon
I think they may have down voted because its not using PHP who knows. Works so thanks.
Cool Hand Luke UK
A: 
$s = substr($string, 0, 261);
$result = substr($s, 0, strrpos($s, ' ');
Zed
A: 

You could do this: Find the first space from the 260th character on and use that as the crop mark:

$pos = strpos($body, ' ', 260);
if ($pos !== false) {
    echo substr($body, 0, $pos);
}
Gumbo
A: 
$pos = strpos($body, $wordfind);
echo substr($body,0, (($pos)?$pos:260));
andres descalzo