在3个单词组中爆炸数组并将其包装

时间:2017-08-31 06:33:51

标签: php explode

我试图在字符串的范围内对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>';
 ?>

4 个答案:

答案 0 :(得分:2)

希望这个会有所帮助。我们在这里使用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>

答案 1 :(得分:0)

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

$html = preg_replace("/(\w+\s\w+(\s\w+\s)?)/", "<span>$1</span>\n", $title_my);

demo

中查看

答案 2 :(得分:0)

你也可以使用它

$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>';

答案 3 :(得分:0)

它没有比这更简单/更有效:

代码:(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>

模式匹配每第三个单词后的空格。此空格已替换为</span><span>。整个字符串前面加<span>并附加</span>以确保所有标记均衡。

我本可以使用:~\S(?:\s\S+){2}\K\s~但捕获组会导致性能下降。

\K表示重新启动全字符串匹配 - 换句话说:“忘记所有匹配的字符到此为止”。