每五个单词分割字符串

5
我希望能够在每五个单词后分割字符串。 示例

这里有一些要打字的内容。这是一个示例文本。

输出
There is something to type
here. This is an example
text

这可以使用preg_split()完成吗?或者在PHP GD中有包装文本的方法吗?
5个回答

6
您可以使用正则表达式。
$str = 'There is something to type here. This is an example text';
echo preg_replace( '~((?:\S*?\s){5})~', "$1\n", $str );

这里需要输入一些内容。这是一个示例文本。

涉及IT技术,无法直接翻译标签的意思,因此保留了HTML标签。

4

这是我尝试翻译的内容,虽然我没有使用 preg_split() 函数

<?php
$string_to_split='There is something to type here. This is an example text';
$stringexploded=explode(" ",$string_to_split);
$string_five=array_chunk($stringexploded,5); 

for ($x=0;$x<count($string_five);$x++){
    echo implode(" ",$string_five[$x]);
    echo '<br />';
    }
?>

3
一个简单的算法是将字符串按所有空格分割,生成一个单词数组。然后您可以简单地循环遍历该数组,并在每5个项目时写入新行。您真的不需要比这更高级的东西。使用str_split来获取数组。

1
可以与 array_chunk 一起使用:http://php.net/manual/zh/function.array-chunk.php - Felix Kling
你也可以在字符串上使用 explode() 函数,使用空格作为分隔符,并继续使用上述描述的技术。PHP 有很多种做同一件事情的方法,这是它的优点。 - EmmanuelG
虽然修改这个不难,但它并没有满足示例中的换行符要求。 - goat
@chris:仅输出中有我回答中提到的新行。示例输入是单行。此外,原帖指出只在空格上分割。更新后的帖子不那么具体。 - Paul Sasik

1

使用 PREG_SPLIT_DELIM_CAPTUREPREG_SPLIT_NO_EMPTY 标志来处理 preg_split() 函数:

<?php
$string = preg_split("/([^\s]*\s+[^\s]*\s+[^\s]*\s+[^\s]*\s+[^\s]*)\s+/", $string, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);

结果

array (
  1 => 'There is something to type',
  2 => 'here. This is an example',
  3 => 'text',
)

0
<?php 
function limit_words ($text, $max_words) {
    $split = preg_split('/(\s+)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
    array_unshift($split,"");
    unset($split[0]);
    $truncated = '';
    $j=1;
    $k=0;
    $a=array();
    for ($i = 0; $i < count($split); $i += 2) {
       $truncated .= $split[$i].$split[$i+1];
        if($j % 5 == 0){
            $a[$k]= $truncated;
            $truncated='';
            $k++;
            $j=0;
        }
        $j++;
    }
    return($a);
}
$text="There is something to type here. This is an example text";

print_r(limit_words($text, 5));



Array
(
    [0] => There is something to type
    [1] =>  here. This is an example
)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接