繁体   English   中英

PHP中更智能的自动换行用于长词?

[英]Smarter word-wrap in PHP for long words?

我正在寻找一种方法让PHP中的自动换行更智能一点。 因此,它不会预先打破长字,只留下任何先前的小字在一行上。

假设我有这个(真正的文本总是完全动态的,这只是为了显示):

wordwrap('hello! heeeeeeeeeeeeeeereisaverylongword', 25, '<br />', true);

这输出:

你好!
heeeeeeeeeeeeeeereisavery
长字

看,它在第一行留下了单词。 我怎样才能让它输出更像这样的东西:

你好! heeeeeeeeeeee
eeereisaverylongword

因此它利用每条线上的任何可用空间。 我已经尝试了几个自定义函数,但没有一个是有效的(或者它们有一些缺点)。

我已经开始使用这个智能文字包装的自定义功能了:

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";

编辑 :发现了一些警告。 对此(以及本机功能)的一个主要警告是缺少多字节支持。

怎么样

$string = "hello! heeeeeeeeeeeeeeereisaverylongword";
$break = 25;

echo implode(PHP_EOL, str_split($string, $break));

哪个输出

hello! heeeeeeeeeeeeeeere                                                                                                                                                           
isaverylongword

str_split()将字符串转换为$ break size块的数组。

implode()使用胶水将数组作为字符串连接在一起,在这种情况下,胶水是行尾标记(PHP_EOL),尽管它可以很容易地成为' <br/> '

这也是一个解决方案(对于浏览器等):

$string = 'hello! heeeeeeeeeeeeeeeeeeeeeereisaverylongword';
echo preg_replace('/([^\s]{20})(?=[^\s])/', '$1'.'<wbr>', $string);

它将<wbr>放在包含20个或更多字符的单词上

<wbr>表示“分词机会”,因此只有在必须时才会中断(由元素/浏览器/查看器/其他的宽度决定)。 否则它是看不见的。

适用于没有固定宽度的流畅/响应式布局。 并不像php的wordwrap那样包裹奇怪

您可以使用CSS来完成此任务。

word-wrap: break-word;

那会打破你的话。 这是一个链接,可以看到它的实际效果:

http://www.css3.info/preview/word-wrap/

这应该是诀窍......

$word = "hello!" . wordwrap('heeeeeeeeeeeeeeereisaverylongword', 25, '<br />', true);
echo $word;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM