tags:

views:

84

answers:

2

Hi guys,

I'm trying to construct a regular expression that would match a pattern as such:

word1, word2, word3

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

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

But this matches only "" several times in a string.

Can someone help me with this please?

+4  A: 

Try

"/^\w+, \w+, \w+$/"
Jens
Yep that works thanks Jens!
Pavel
+7  A: 

It depends what you mean by "word" but you can start by trying 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 definitions of "word":

  • Anything except whitespace or comma: [^\s,]+
  • Only letters in A-Z: [A-Z]+ (optionally add case-insensitive flag)
  • Any letter in Unicode in any language: \p{L}+ (not widely supported)
  • Etc...
Mark Byers
Good explanation of the code. Very helpful for budding programmers that need such explanations.
matsolof