Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 检查字符串是否与模式匹配_Php_Regex_String - Fatal编程技术网

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

Php 检查字符串是否与模式匹配,php,regex,string,Php,Regex,String,如果我需要一个字符串来匹配这个模式:“word1,word2,word3”,在PHP中如何检查字符串以确保它符合这个模式 我要确保字符串符合以下任何模式: word word1,word2 word1,word2,word3, word1,word2,word3,word4,etc. 使用: 这符合: stack,over,flow I'm,not,sure 但不是: , asdf two,words four,or,more,words empty,word, 如果您严格希望匹配一个或多

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

我要确保字符串符合以下任何模式:

word
word1,word2
word1,word2,word3,
word1,word2,word3,word4,etc.
使用:

这符合:

stack,over,flow
I'm,not,sure
但不是:

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

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

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

当我需要确保我的整个字符串与模式匹配时,我会执行以下操作:

例如,我想要一个Y-m-d日期(不是Y-m-d H:I:s)


我不认为这是他的意思,对此我很抱歉。使用多种语言的副作用。Ruby将接受文本。(或将“”解释为delimeters。)应使用
^
$
检查字符串是否与模式完全匹配
^
标记字符串的开头,$标记字符串的结尾。在您的示例中,正则表达式模式如下:
“/^[1-9][0-9]{3}-(0[1-9]|1[0-2])-([012][1-9]|3[01])$/”
,只有当整个字符串与模式匹配时才会匹配。@pascscha但他/她使用
$matches[0]====$str
,
asdf
two,words
four,or,more,words
empty,word,
  preg_match("^(?:\w+,)*\w+$", $input)
$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