PHP 8.5.0 Beta 1 available for testing

Voting

: min(five, two)?
(Example: nine)

The Note You're Voting On

zac dot hester at gmail dot com
10 years ago
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" );
?>

<< Back to user notes page

To Top