用PHP换行可以更智能地换长字吗? [英] Smarter word-wrap in PHP for long words?
问题描述
我正在寻找一种使PHP中的自动换行更加智能的方法.因此,它不会预先打断长单词,而不会在一行上留下任何先前的小单词.
I'm looking for a way to make word-wrap in PHP a bit smarter. So it doesn't pre-break long words leaving any prior small words alone on one line.
假设我有这个(真实文本始终是完全动态的,这只是为了显示):
Let's say I have this (the real text is always completely dynamic, this is just to show):
wordwrap('hello! heeeeeeeeeeeeeeereisaverylongword', 25, '<br />', true);
这将输出:
你好!
heeeeeeeeeeeeeeeeereisavery
长字
hello!
heeeeeeeeeeeeeeereisavery
longword
看,它把小词放在第一行. 我如何得到这样的输出:
See, it leaves the small word alone on the first line. How can I get it to ouput something more like this:
你好! heeeeeeeeeeee
eeereisaverylongword
hello! heeeeeeeeeeee
eeereisaverylongword
因此,它利用了每一行上的任何可用空间.我尝试了几种自定义功能,但没有一个有效(或者它们有一些缺点).
So it utilizes any available space on each line. I have tried several custom functions, but none have been effective (or they had some drawbacks).
推荐答案
我已经使用了此智能自动换行的自定义功能:
I've had a go at the custom function for this smart wordwrap:
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";
编辑:发现了一些警告.对此(以及本机功能)的一个主要警告是缺少多字节支持.
EDIT: Spotted a couple of caveats. One major caveat with this (and also with the native function) is the lack of multibyte support.
这篇关于用PHP换行可以更智能地换长字吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!