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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1777101/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:48:12  来源:igfitidea点击:

Check to see if a string matches a pattern

phpregexstring

提问by Andrew

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?

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

I want to make sure the string fits any of these patterns:

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

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

回答by phihag

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,

回答by Scott Evernden

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

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

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

回答by chiliNUT

When I need to make sure that my entire string matches a pattern, I do this:

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

ex, I want a Y-m-d date (not Y-m-d H:i:s)

例如,我想要一个 Ymd 日期(不是 Ymd 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