note 116865 added to function.wordwrap
| From: | zac dot hester at gmail dot com | Date: | Thu, 12 Mar 2015 14:28:31 +0000 |
| Subject: | note 116865 added to function.wordwrap | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-201927@lists.php.net to get a copy of this message | ||
I recently ran into the issue discussed by another contributor to this function (frans-jan at
van-steenbeek dot R-E-M-O-V-E dot net). The problem appeared to be how wordwrap() was treating
white space. Instead of writing my own version of wordwrap(), I discovered that the
"break" parameter is not only used as the inserted string, but also used to detect the
existing wrap delimiters (e.g. line endings). If you can manage to "normalize" the wrap
delimiters in your original string, you don't need to try to work-around the function wrapping
at seemingly odd places (like immediately after one short word). As one quick-and-dirty way to get
wordwrap() to play nicely with most use-cases, I did this:
<?php
$break = strpos( $content, "\r" ) === false ? "\n" : "\r\n";
$content = wordwrap( $content, 78, $break );
?>
I also tend to normalize multi-line strings (if my OCD is acting up). You would typically perform
this conversion _before_ sending it off to wordwrap().
<?php
//quick and simple, but clobbers old-style Mac line-endings
$content = str_replace( "\r", '', $content );
//slower, but works with everything
$content = preg_replace( "/(\r\n|\r)/", "\n", $content );
//now, wordwrap() will behave exactly as expected
$content = wordwrap( $content, 78, "\n" );
?>
----
Server IP: 72.52.91.14
Probable Submitter: 199.87.127.129
----
Manual Page -- http://php.net/manual/en/function.wordwrap.php
Edit -- https://master.php.net/note/edit/116865
Del: integrated -- https://master.php.net/note/delete/116865/integrated
Del: useless -- https://master.php.net/note/delete/116865/useless
Del: bad code -- https://master.php.net/note/delete/116865/bad+code
Del: spam -- https://master.php.net/note/delete/116865/spam
Del: non-english -- https://master.php.net/note/delete/116865/non-english
Del: in docs -- https://master.php.net/note/delete/116865/in+docs
Del: other reasons-- https://master.php.net/note/delete/116865
Reject -- https://master.php.net/note/reject/116865
Search -- https://master.php.net/manage/user-notes.php