thiebo
thiebo

Reputation: 1435

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.

Upvotes: 0

Views: 327

Answers (2)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

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,}

Upvotes: 1

Sjon
Sjon

Reputation: 5155

Let's ignore the fact that if you want to check exactly what you're posting, it'd be more efficient to compare strpos($subject, ', ') != strrpos($subject, ', ').

There are 2 problems with your regexp, the repetition is applied to the space only (not the sequence) plus you leave no room for any other characters, so your regexp currently checks if your subject contains ,<SP><SP>

Fixing both issues would lead to:

var_dump(preg_match('~(, .*){2,}~', $subject));

Upvotes: 1

Related Questions