开发者

Check to see if a string matches a pattern

开发者 https://www.devze.com 2022-12-11 22:45 出处:网络
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?

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.


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,


preg_match('/word[0-9]/', $string);

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


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

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

精彩评论

暂无评论...
验证码 换一张
取 消