如何在由空格分割的字符串的中点添加换行符 [英] How do I add a line break at the mid point of a string split by whitespace

查看:23
本文介绍了如何在由空格分割的字符串的中点添加换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 php:如何在位于字符串相对中间的空白处插入换行符?或者换句话说,我如何计算一个句子中的单词,然后在句子的中途换行?

Using php: How can I insert a line break at the whitespace that falls in the relative middle of string? Or in other words, how do I count the words in a sentence and then put a line break in the sentence at the halfway point?

这个想法是为了避免在博客文章标题的第二行出现寡妇(被遗弃的词),方法是将每个标题切成两半,如果标题超过一行,则将其放在两行.

The idea is to avoid widows (abandoned words) on the second line of blog article titles by essentially cutting each title in half and putting it on two line if the title takes up more than one line.

提前致谢.

更新:大家好,我意识到我需要 preg_split 函数来按空格分割标题.抱歉,如果该部分在问题中不清楚.我修改了 Asaph 的答案并使用了这个:

Update: Hi All, I realized I needed the preg_split function to split the title by whitespaces. Sorry if that part was not clear in the question. I modified Asaph's answer and used this:

$title_length = strlen($title);
if($title_length > 30){
    $split = preg_split('/ /', $title, null, PREG_SPLIT_NO_EMPTY);
    $split_at = ceil(count($split) / 2);
    echo $split_at;
    $broken_title = '';
    $broken = false;
    foreach($split as $word_pos => $word){
        if($word_pos == $split_at  && $broken == false){
            $broken_title.= '<br />'."\n";
            $broken = true;
        }
        $broken_title .= $word." ";
    }
    $title = $broken_title;
}   

我是 SO 的新手,我被社区的力量所震撼.干杯.

I'm new to SO and I'm blown away by the power of the community. Cheers.

推荐答案

使用 PHP 的 wordwrap() 函数.您可以使用字符串的长度除以 2 作为第二个参数.下面是一个例子:

Use PHP's wordwrap() function. You can use your string's length divided by 2 as the 2nd argument. Here is an example:

<?php
$sentence = 'This is a long sentence that I would like to break up into smaller pieces.';
$width = strlen($sentence)/2;
$wrapped = wordwrap($sentence, $width);
echo $wrapped;
?>

它输出:

This is a long sentence that I would
like to break up into smaller pieces.

如果你想要 HTML 输出,你可以使用可选的第三个参数来指定中断字符.像这样:

If you want HTML output, you can use the optional 3rd argument to specify the break characters. Like this:

$wrapped = wordwrap($sentence, $width, '<br />');

这篇关于如何在由空格分割的字符串的中点添加换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆