Search code examples
phppreg-split

preg_split returns a non expected number


my first question, so please be patient with me...

I have this string:

"Create a script which will take a string and analyse it to produce the following stats. Spicy jalapeno bacon ipsum dolor amet kevin buffalo frankfurter, sausage jerky pork belly bacon. Doner sausage alcatra short loin, drumstick ham tenderloin shank bresaola porchetta meatball jowl ribeye ground round. Ribeye pork loin filet mignon, biltong shoulder short ribs tongue ball tip drumstick ground round rump pork chop. Kielbasa bacon strip steak andouille ham short ribs short loin venison frankfurter spare ribs doner corned beef."

I used this function:


$sentenceArray = preg_split('/[.]+/', $string);

foreach ($sentenceArray as $sentence) {
    $numberOfWords = str_word_count($sentence);
    echo '<br>' . $numberOfWords . '<br>';
}

and I get this:

16

14

16

18

17

0

I am expecting 16, 14, 16, 18, 17 but I don't understand where the 0 is coming from?! Many thanks!


Solution

  • This happens because your input string ends with a point, and preg_split will split at that point too, generating the string that follows it as a split off, which is the empty string.

    Use preg_match_all instead. This function will give the result array as an argument, not as return value, and that array will be wrapped. So do:

    preg_match_all('/[^.]+/', $string, $sentenceArray);
    foreach ($sentenceArray[0] as $sentence) {
        $numberOfWords = str_word_count($sentence);
        echo '<br>' . $numberOfWords . '<br>';
    }