检查字符串是否与模式匹配

时间:2009-11-21 23:08:52

标签: php regex string

如果我需要一个字符串来匹配这个模式:“word1,word2,word3”,我将如何检查字符串以确保它符合PHP格式?

我想确保字符串适合任何这些模式:

word
word1,word2
word1,word2,word3,
word1,word2,word3,word4,etc.

4 个答案:

答案 0 :(得分:14)

使用regular expressions

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

匹配:

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

但不是:

,
asdf
two,words
four,or,more,words
empty,word,

答案 1 :(得分:2)

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

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

答案 2 :(得分:2)

如果您严格要匹配一个或多个完整单词而不是逗号分隔的短语,请尝试:

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

答案 3 :(得分:0)

当我需要确保我的整个字符串与模式匹配时,我这样做:

前,我想要一个Y-m-d日期(不是Y-m-d H:i:s)

$date1="2015-10-12";
$date2="2015-10 12 12:00:00";

function completelyMatchesPattern($str, $pattern){
    return preg_match($pattern, $str, $matches) === 1 && $matches[0] === $str;
}

$pattern="/[1-9][0-9]{3}-(0[1-9]|1[0-2])-([012][1-9]|3[01])/";

completelyMatchesPattern($date1, $pattern); //true
completelyMatchesPattern($date2, $pattern); //false