每五个单词后拆分字符串


Split string after every five words

我想在每五个单词之后拆分一个字符串。

这里有一些东西要输入。这是一个示例文本

输出

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

如何使用preg_split()做到这一点?或者有什么方法可以在 PHP GD 中换行文本?

您也可以

使用正则表达式

$str = 'There is something to type here. This is an example text';
echo preg_replace( '~((?:'S*?'s){5})~', "$1'n", $str );

这里有一些东西要输入
。这是一个示例
文本

这是我

的尝试,尽管我没有使用preg_spilt()

<?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 />';
    }
?>

一个简单的算法是在所有空格上拆分字符串以生成单词数组。然后,您可以简单地遍历数组并每 5 项写入一个新行。你真的不需要比这更花哨的东西了。使用 str_split 获取数组。

使用 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',
)
<?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
)