4

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

例子

有东西可以在这里输入。这是一个示例文本

输出

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

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

4

5 回答 5

4

您也可以使用正则表达式

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

有东西可以
在这里输入。这是一个示例
文本

于 2012-05-11T17:32:46.807 回答
3

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

于 2012-05-11T17:10:12.267 回答
3

这是我的尝试,虽然我没有使用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 />';
    }
?>
于 2012-05-11T18:35:36.937 回答
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',
)
于 2012-05-11T17:42:54.653 回答
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
)
于 2014-06-11T05:54:47.523 回答