Check if the string matches the pattern

If I need a string to match this pattern: "word1, word2, word3", how would I check the string to make sure it matches this, in PHP?

I want to make sure that the string matches any of these patterns:

word word1,word2 word1,word2,word3, word1,word2,word3,word4,etc. 
+6
string php design-patterns
source share
4 answers

Use regular expressions :

 preg_match("[^,]+(,[^,]+){2}", $input) 

It corresponds:

 stack,over,flow I'm,not,sure 

But not:

 , asdf two,words four,or,more,words empty,word, 
+9
source share
 preg_match('/word[0-9]/', $string); 

http://php.net/manual/en/function.preg-match.php

+2
source share

if you strictly want to match one or more whole words, not commas, try:

  preg_match("^(?:\w+,)*\w+$", $input) 
+1
source share

When I need to make sure that my entire string matches the pattern, I do this:

ex, I need the date Ymd (not Ymd H: i: s)

 $date1="2015-10-12"; $date2="2015-10 12 12:00:00"; function completelyMatchesPattern($str, $pattern){ return preg_match($pattern, $str, $matches) === 1 && $matches[0] === $str; } $pattern="/[1-9][0-9]{3}-(0[1-9]|1[0-2])-([012][1-9]|3[01])/"; completelyMatchesPattern($date1, $pattern); //true completelyMatchesPattern($date2, $pattern); //false 
0
source share

All Articles