How to avoid / work around PHP wordwrap removing spaces

y3bcpkx1  于 2022-10-22  发布在  PHP
关注(0)|答案(3)|浏览(104)

For an iCal generator that I'm working on, I need to ensure that each 75 characters, a string is broken like this:

$string = "This is a long text. I use this text to demonstrate the PHP wordwrap function.";
$newstring = wordwrap($string, 75, "\r\n ", TRUE);

echo($newstring);

Result:

This is a long text. I use this text to demonstrate the PHP wordwrap
 function.

iCal interprets the first space (from the wordwrap break parameter) as an indicator that the text property continues.
The wordwrap function removed the second space (from the string). After decoding the iCal content, the text would therefore look like this:

This is a long text. I use this text to demonstrate the PHP wordwrapfunction.

How can I work around this? I don't want the space from the string (between "wordwrap" and "function") to be removed.

ibps3vxo

ibps3vxo1#

I have to use chunk_split instead. It will preserve the space and also not try to wrap at a space, which I don't need.

$string = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaannnnnn";
$newstring = rtrim(chunk_split($string, 75, "\r\n "), "\r\n ");

echo($newstring);

Space preserved:

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
  aaaaannnnnn

rtrim is also used, as chunk_split always appends end .
This won't count the space within end , however. So if there are multiple lines, one could actually be 76 chars long. I changed the chunklen parameter to 74, as this is good enough for my use case.

q9rjltbz

q9rjltbz2#

Ok, While doing wordwrap pass an additional space so, that space between wordwrap and function will be retained.
Use this

$newstring = wordwrap($string, 75, " \r\n", TRUE);

Instead of

$newstring = wordwrap($string, 75, "\r\n", TRUE);

Output Before iCal:

This is a long text. I use this text to demonstrate the PHP wordwrap 
function.

Output After iCal:

This is a long text. I use this text to demonstrate the PHP wordwrap function.
w6mmgewl

w6mmgewl3#

It will always remove spaces, it's better to do your own function.
This will also ignore HTML tags.

function shyLongWords($str, $len = 40) {
    $str = preg_replace_callback('#((?:(?!<[/a-z]).)*)([^>]*>|$)#si', function($m) use ($co, $len) {
        $x = '';
        foreach (explode(' ', $m[1]) as $i => $part) {
            $x.= ($i == 0 ? '' : ' ').implode("&shy;", str_split($part, $len));
        }
        return $x . $m[2];
    }, $str);
    return $str;
}

相关问题