每五个单词后拆分字符串

时间:2012-05-11 17:05:57

标签: php preg-split

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

示例

  

这里可以输入一些内容。这是一个示例文本

输出

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

如何使用preg_split()完成此操作?或者有没有办法在PHP GD中包装文本?

5 个答案:

答案 0 :(得分:4)

您也可以使用正则表达式

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

这里有什么要打字的。这是一个例子

答案 1 :(得分:3)

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

答案 2 :(得分:2)

这是我对此的尝试,虽然我没有使用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 />';
    }
?>

答案 3 :(得分:1)

使用preg_split()PREG_SPLIT_DELIM_CAPTUREPREG_SPLIT_NO_EMPTY标记:

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

答案 4 :(得分: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
)