Check to see if a string matches a pattern


Question

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
10
10/26/2018 6:55:51 PM

Accepted Answer

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,
14
11/23/2009 10:13:19 PM

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon