You need a regular expression that matches "word1, word2, word3"

I am trying to build a regex that will match the pattern as such:

word1, word2, word3 

So basically I want " , " to appear twice and have words between them. So far I have come up with:

 $general_content_check = preg_match("/^.*, .*$/", $general_content); 

But this number only matches " , " several times per line.

Can anyone help me with this?

+4
source share
2 answers

Try

 "/^\w+, \w+, \w+$/" 
+4
source

It depends on what you mean by the word, but you can start with this:

 ^[^,]+(?:, +[^,]+){2}$ 

Explanation:

  ^ Start of line / string.
 [^,] + A "word" (anything that isn't a comma - including whitespace, etc.)
 (?: Start non-capturing group
     , + A comma then any number of spaces
     [^,] + A word
 ) Close group
 {2} Repeat group exactly two times
 $ End of line / string.

Other possible word definitions:

  • Everything except spaces or comma: [^\s,]+
  • Letters in AZ only: [AZ]+ (optionally add a case-insensitive flag)
  • Any letter in Unicode in any language: \p{L}+ (not widely supported)
  • Etc ...
+7
source

All Articles