php 如何在由空格分隔的字符串的中间添加换行符

acruukt9  于 2023-01-01  发布在  PHP
关注(0)|答案(3)|浏览(161)

使用php:我怎样在字符串中间的空白处插入一个换行符?或者换句话说,我怎样计算一个句子中的单词数,然后在句子的中间点插入一个换行符?
这个想法是为了避免在博客文章标题的第二行出现寡妇(废弃的单词),基本上是把每个标题切成两半,如果标题占用了超过一行的话,就把它放在两行上。
先谢了。
更新:大家好,我意识到我需要preg_split函数来用空格分隔标题。如果这部分在问题中不清楚,对不起。我修改了Asaph的答案,并使用了以下内容:

$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的新手,我被社区的力量所震撼。干杯。

jtjikinw

jtjikinw1#

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

<?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输出,你可以使用可选的第三个参数来指定分隔符,如下所示:

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

dkqlctbz2#

    • 已更新**
<?php
$Sentence = 'I will go to the school tomorrow if it is not raining outside and if David is ok with it.';
$Split = explode(' ', $Sentence);

$SplitAt = 0;
foreach($Split as $Word){
    $SplitAt+= strlen($Word)-1;
    if($SplitAt >= strlen($Sentence)){
        break;
    }
}

$NewSentence = wordwrap($Sentence, $SplitAt, '<br />' . PHP_EOL);

echo $NewSentence;
?>

生成以下内容:
如果不是我明天就去学校\n
外面在下雨大卫是否能接受。

    • EDIT**:添加了PHP_EOL以匹配所有系统和html
wwtsj6pe

wwtsj6pe3#

解如果要选择的行数。

function splitSentence($sentence, $lines) {

    $words                  = explode(' ', $sentence);
    $max_line_length        = intval((strlen($sentence) / $lines));
    $current_line_length    = 0;
    $output                 = '';

    foreach ($words as $word) {
    
        $word_length = strlen($word) + 1; // 1 for removed whitespace

        if (($current_line_length + $word_length) <= $max_line_length) {
            $output .= $word.' ';
            $current_line_length += $word_length;
        }
        else {
            $output .= $word.'<br>';
            $current_line_length = 0;
        }
    }

    return $output;
}

相关问题