在 3 个单词的组中分解数组并将其包装

Explode array in the group of 3 words and wrap it

我正在尝试将字符串中的 3 个单词分组。例如我有一个标题

$string = "one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen";

结果输出:

<span>one two three</span>
<span>four five six</span>
<span>seven eight nine</span>
<span>ten eleven twelve</span>
<span>thirteen fourteen fifteen</span>
<span>sixteen seventeen</span>

这是代码

<?php
$title_my = 'one two three four five six seven eight nine ten eleven 
twelve thirteen fourteen fifteen sixteen seventeen';
$word_count = str_word_count($title_my);
/****/
if($word_count < 5):
 $word_i = '12';
else:
 $word_i = '13';
endif;
/****/
$lines = explode("\n", wordwrap($title_my,$word_i, "\n"));
echo '<pre>';
 $i = 1;
 foreach ($lines as &$value) {
  echo '<span class="green'.$i.'">'.$value.' </span>';
 }
 echo '</pre>';
 ?>

希望这篇文章对您有所帮助。这里我们使用 explodeimplodearray_maparray_chunk

Try this code snippet here

<?php

$string="one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen";
$data=array_chunk(explode(" ", $string),3);//splitting words into group of 3
$data=array_map(function($value){
    return sprintf("<span>%s</span>",implode(" ",$value)) ; //adding span tags around it.
},$data);

echo implode("\n",$data);

输出:

<span>one two three</span>
<span>four five six</span>
<span>seven eight nine</span>
<span>ten eleven twelve</span>
<span>thirteen fourteen fifteen</span>
<span>sixteen seventeen</span>

您也可以使用正则表达式来完成这项工作。在 php preg_replace().

中使用正则表达式
$html = preg_replace("/(\w+\s\w+(\s\w+\s)?)/", "<span></span>\n", $title_my);

demo

中查看

也可以用

$title_my = 'one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen';
$lines = explode(" ", $title_my);
$group=3;
$k=1;
echo '<pre>';
for ($i = 0; $i < count($lines); $i = $i + $group) {
    echo '<span class="green' . $k . '">';
    for ($j = $i; $j < $i + $group; $j++) {
        if (isset($lines[$j])) {
            echo $lines[$j]." ";
        }
    }
    echo ' </span></br>';
    $k++;
}
echo '</pre>';

没有比这更简单/更有效的了:

代码:(Demo)

$title_my = 'one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen';
echo '<span>' , preg_replace('~\S+\s\S+\s\S+\K\s~', "</span><span>", $title_my) , '</span>';

输出:

<span>one two three</span>
<span>four five six</span>
<span>seven eight nine</span>
<span>ten eleven twelve</span>
<span>thirteen fourteen fifteen</span>
<span>sixteen seventeen</span>

模式匹配每三个单词后的 space。 space 被 </span><span> 代替。整个字符串以 <span> 开头并附加 </span> 以确保所有标签都是平衡的。

我本可以使用:~\S(?:\s\S+){2}\K\s~ 但是捕获组会拖累性能。

\K 表示重新开始全字符串匹配——换句话说:"forget all matched characters up to this point".