我有一个连接所述阵列回到一起作为一个字符串在去自定义函数为这个智能自动换行:
function smart_wordwrap($string, $width = 75, $break = "\n") {
// split on problem words over the line length
$pattern = sprintf('/([^ ]{%d,})/', $width);
$output = '';
$words = preg_split($pattern, $string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
foreach ($words as $word) {
if (false !== strpos($word, ' ')) {
// normal behaviour, rebuild the string
$output .= $word;
} else {
// work out how many characters would be on the current line
$wrapped = explode($break, wordwrap($output, $width, $break));
$count = $width - (strlen(end($wrapped)) % $width);
// fill the current line and add a break
$output .= substr($word, 0, $count) . $break;
// wrap any remaining characters from the problem word
$output .= wordwrap(substr($word, $count), $width, $break, true);
}
}
// wrap the final output
return wordwrap($output, $width, $break);
}
$string = 'hello! too long here too long here too heeeeeeeeeeeeeereisaverylongword but these words are shorterrrrrrrrrrrrrrrrrrrr';
echo smart_wordwrap($string, 11) . "\n";
编辑:发现了一个警告夫妇。与此(也与本机功能)一个主要的警告是缺乏多字节支持。
我刚刚从Google来到这里。我很惊讶,这不起作用。这是PHP内置函数的错误吗?在我看来,当你将最后一个参数设置为true时,它应该使用所有可用的空间。为什么不这样做? – 2016-10-19 18:47:24
@安德鲁是啊,我不知道。你可以使用CSS wrap方法,或者这个http://stackoverflow.com/questions/9815040/smarter-word-wrap-in-php-for-long-words/25273135#25273135(如果是网页浏览等)。和平 – mowgli 2016-10-19 23:28:01