PHP 8.4.24 Released!

Voting

: five minus one?
(Example: nine)

The Note You're Voting On

michdingpayc
4 years ago
A correction to ju1ius' utf-8 safe wordwrap from 10 years ago. 
This version addresses issues where breaks were not being added to the first and last words in the input string.

<?php
function utf8_wordwrap($string, $width=75, $break="\n", $cut=false)
{
  if($cut) {
    // Match anything 1 to $width chars long followed by whitespace,
    // 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 lookbehind
    // to avoid crazy backtracking when words are longer than $width
    $search= '/(?<=\s|^)(.{1,'.$width.'}\S*)(?:\s)/uS';
    $replace = '$1'.$break;
  }
  return preg_replace($search, $replace, $string);
}
?>

<< Back to user notes page

To Top