views:

98

answers:

3

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

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

word
word1,word2
word1,word2,word3,
word1,word2,word3,word4,etc.
+1  A: 
preg_match('/word[0-9]/', $string);

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

CodeJoust
does php support regex literals? last time i had to use strings...
knoopx
I don't think that this is what he meant.
Mark Byers
Sorry about that. The side-effect of using multiple langages. Ruby will take the literal. (or interpret the '' as delimeters.)
CodeJoust
+3  A: 

Use regular expressions:

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

This matches:

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

But not:

,
asdf
two,words
four,or,more,words
empty,word,
phihag
How could you make it work with any number of words?
Andrew
Change the `{2}` to a `*`
Blair McMillan
Oh, alright. Thanks. :)
Andrew
+1  A: 

if you strictly want to match one or more whole words and not comma-separated phrases try:

  preg_match("^(?:\w+,)*\w+$", $input)
Scott Evernden