tags:

views:

55

answers:

2

Okay, I am a noob to regex, and I am using this site for my regex primer:

Question: using the s modifier, the code below is suppose to echo 4 as it has found 4 newline characters.

However, when I run this I get one(1), why?

link text

 <?php
 /*** create a string with new line characters ***/
    $string = 'sex'."\n".'at'."\n".'noon'."\n".'taxes'."\n";

    /*** look for a match using s modifier ***/
    echo preg_match("/sex.at.noon/s", $string, $matches);

    /*The above code will echo 4 as it has found 4 newline characters.*/

?>
+6  A: 

Use preg_match_all() instead which doesn't stop after the first match.

preg_match() returns the number of times pattern matches. That will be either 0 times (no match) or 1 time because preg_match() will stop searching after the first match. preg_match_all() on the contrary will continue until it reaches the end of subject . preg_match() returns FALSE if an error occurred. —PHP.net

However, the code will output still only 1 because what you are matching is the regex "sex.at.noon" and not a line break.

Joey
Thanks, totally forget about that either it's 0 times which means no match or a 1 which means there was a match. So why does the author state I am suppose to get 4, see attached link?
Newb
That's a good question. I'd assume he simply made a mistake and previously matched something like `.$`
Joey
+1  A: 

preg_match() will only ever return 0 or 1 because it stops after the first time the pattern matches. If you use preg_match_all() it will still return 1 because your pattern only matches once in the string you're matching against.

If you want the number of newlines via regex:

echo preg_match_all("/\n/m", $string, $matches);

Or via string functions:

echo substr_count($string, "\n");
scribble