ForALLs
ForALLs

Reputation: 27

PHP split string to next period (.)

My aim is to split string after every 7 words. If the 7th word has a comma (,), move to the next word with period (.) or exclamation (!)

So far, I've been able to split string by 7 words, but cannot check if it contains commas (,) or move to the next word with . or !

   $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 expect

I have a feeling about the rain, let us ride.

He figured I was only joking.

But the actual output is

I have a feeling about the rain,

let us ride. He figured I was

only joking.

Upvotes: 0

Views: 147

Answers (1)

Nick
Nick

Reputation: 147166

Here's one way to do what you want. Iterate through the list of words, 7 at a time. If the 7th word ends with a comma, increase the list pointer until you reach a word ending with a period or exclamation mark (or the end of the string). Output the current chunk. When you reach the end of the string, output any remaining words.

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

Output:

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

Demo on 3v4l.org

Upvotes: 1

Related Questions