note 107570 added to function.wordwrap

From: Date: Sat, 18 Feb 2012 03:58:49 +0000
Subject: note 107570 added to function.wordwrap
Groups: php.notes 
Request: Send a blank email to php-notes+get-186204@lists.php.net to get a copy of this message
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. ---- Server IP: 195.221.21.36 Probable Submitter: 82.226.98.63 ---- Manual Page -- http://www.php.net/manual/en/function.wordwrap.php Edit -- https://master.php.net/note/edit/107570 Del: integrated -- https://master.php.net/note/delete/107570/integrated Del: useless -- https://master.php.net/note/delete/107570/useless Del: bad code -- https://master.php.net/note/delete/107570/bad+code Del: spam -- https://master.php.net/note/delete/107570/spam Del: non-english -- https://master.php.net/note/delete/107570/non-english Del: in docs -- https://master.php.net/note/delete/107570/in+docs Del: other reasons-- https://master.php.net/note/delete/107570 Reject -- https://master.php.net/note/reject/107570 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#186204) next »