php拆分字符串到下一个周期(.)



我的目的是每7个单词后拆分字符串。如果第7个单词具有逗号(,(,请转到带有周期(。(或感叹号(!(

的下一个单词

到目前为止,我已经能够用7个单词将字符串拆分,但是无法检查它是否包含逗号(,(或使用下一个单词。或!

   $string = "I have a feeling about the rain, let us ride. He figured I was only joking.";
   $explode = explode(" ", $string);
   $chunk_str = array_chunk($explode, 7);
   for ($x=0; $x<count($chunk_str); $x++)
   {
       $strip = implode(" ",$chunk_str[$x]);
       echo $strip.'<br><br>';
   }

我期望

I have a feeling about the rain, let us ride.
He figured I was only joking.

但实际输出是

I have a feeling about the rain,
let us ride. He figured I was
only joking.

这是做您想做的事情的一种方法。遍历单词列表,一次。如果第7个单词以逗号结尾,请增加列表指针,直到您以期间或感叹号结尾(或字符串的结尾(结尾为止。输出当前块。当您到达字符串的末端时,输出所有剩下的单词。

$string = "I have a feeling about the rain, let us ride. He figured I was only joking.";
$explode = explode(' ', $string);
$num_words = count($explode);
if ($num_words < 7) {
    echo $string;
}
else {
    $k = 0;
    for ($i = 6; $i < count($explode); $i += 7) {
        if (substr($explode[$i], -1) == ',') {
            while ($i < $num_words && substr($explode[$i], -1) != '.' && substr($explode[$i], -1) != '!') $i++;
        }
        echo implode(' ', array_slice($explode, $k, $i - $k + 1)) . PHP_EOL;
        $k = $i + 1;
    }
}
echo implode(' ', array_slice($explode, $k)) . PHP_EOL;

输出:

I have a feeling about the rain, let us ride. 
He figured I was only joking.

3v4l.org上的演示

最新更新