note 127205 added to function.wordwrap
| From: | michdingpayc at main dot php dot net | Date: | Thu, 30 Jun 2022 19:23:08 +0000 |
| Subject: | note 127205 added to function.wordwrap | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-218785@lists.php.net to get a copy of this message | ||
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);
}
?>
----
Server IP: 45.112.84.4
Probable Submitter: 45.91.157.133 (proxied: 67.200.201.137)
----
Manual Page -- https://php.net/manual/en/function.wordwrap.php
Edit -- https://main.php.net/note/edit/127205
Del: integrated -- https://main.php.net/note/delete/127205/integrated
Del: useless -- https://main.php.net/note/delete/127205/useless
Del: bad code -- https://main.php.net/note/delete/127205/bad+code
Del: spam -- https://main.php.net/note/delete/127205/spam
Del: non-english -- https://main.php.net/note/delete/127205/non-english
Del: in docs -- https://main.php.net/note/delete/127205/in+docs
Del: other reasons-- https://main.php.net/note/delete/127205
Reject -- https://main.php.net/note/reject/127205
Search -- https://main.php.net/manage/user-notes.php