PHP 8.4.24 Released!

Voting

: six minus three?
(Example: nine)

The Note You're Voting On

ju1ius
14 years ago
Another solution to utf-8 safe wordwrap, unsing regular expressions.
Pretty good performance and works in linear time.

<?php
function utf8_wordwrap($string, $width=75, $break="\n", $cut=false)
{
  if($cut) {
    // Match anything 1 to $width chars long followed by whitespace or EOS,
    // otherwise match anything $width chars long
    $search = '/(.{1,'.$width.'})(?:\s|$)|(.{'.$width.'})/uS';
    $replace = '$1$2'.$break;
  } else {
    // Anchor the beginning of the pattern with a lookahead
    // to avoid crazy backtracking when words are longer than $width
    $pattern = '/(?=\s)(.{1,'.$width.'})(?:\s|$)/uS';
    $replace = '$1'.$break;
  }
  return preg_replace($search, $replace, $string);
}
?>
Of course don't forget to use preg_quote on the $width and $break parameters if they come from untrusted input.

<< Back to user notes page

To Top