Search code examples
phppreg-match

php preg_match testing commas more than twice


I have this:

$subject ="bla foo bar, blafoo, blabla, ";
$pattern = '/, {2,}/';
if (preg_match($pattern, $subject)){
    echo "true";
    }else{   
    echo "false";
    }

I want to test whether comma+space occurs twice or more often in the subject. However, the above returns false. So I'm doing something wrong.


Solution

  • Since you are looking for a literal substring, use substr_count:

    if (substr_count($subject, ', ') > 2) {
    ...
    } else {
    ...
    }
    

    If you want to do the same but this time with a regex, use preg_match_all that returns the number of occurrences in the same way.

    To repeat several characters/tokens in the pattern itself, you need to group them. You can use a non-capturing group (?:...):

    (?:, ){2,}
    

    Without a group, only the last token is repeated. (so the space in your example).

    But this pattern doesn't describe your string since there are other character between the commas, you must add them:

    (?:, [^,]*){2,}