Thursday, July 19, 2012

Substract a string on a word boundry using regexp

There are many answers on this problem, but i found one very easy to implement, lightweight, and fast.
I think the fewer code lines, the better, so why not using a regexp instead of substr?

The function looks like this:
  function substr_wb($string, $length){
    preg_match("/^(.{1,$length})\b/u", $string, $matches);
    return $matches[1];
  }

No comments:

Post a Comment