Break word boundary
Posted: Sun Mar 09, 2008 11:24 pm
Quite often I need to break long strings of text on word boundaries. I have a perl function that does this nicely with regex, but it seems to fail in php despite numerous tries to make it work. As a result, I came up with the function below. It seems to work and I thought the world needed to know.
static public function shortenWordBoundary($h, $m) {
if (strlen($h) <= $m) return $h;
$h = substr($h, 0, $m+1);
$n = preg_replace("/^(.+)\s.*/s", '$1', $h);
if ($n) return "$n...";
else return $h;
}
static public function shortenWordBoundary($h, $m) {
if (strlen($h) <= $m) return $h;
$h = substr($h, 0, $m+1);
$n = preg_replace("/^(.+)\s.*/s", '$1', $h);
if ($n) return "$n...";
else return $h;
}