Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check to see if a string matches a pattern

Tags:

string

regex

php

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.
like image 821
Andrew Avatar asked Nov 21 '09 23:11

Andrew


1 Answers

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,
like image 101
phihag Avatar answered Sep 23 '22 14:09

phihag