Making sure PHP substr finishes on a word not a character Making sure PHP substr finishes on a word not a character php php

Making sure PHP substr finishes on a word not a character


substr($body, 0, strpos($body, ' ', 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:

$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.


You can try this:

   $s = substr($string, 0, 261);   $result = substr($s, 0, strrpos($s, ' '));