我的目标是每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.
答案 0 :(得分:1)
这是做您想要的事情的一种方法。一次遍历单词列表一次,每次7次。如果第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.