php 在 if 语句条件中使用正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6390375/
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-26 00:13:32  来源:igfitidea点击:

using regular expressions in if statement conditions

phpregexif-statement

提问by Alex Getty

i am trying to get a php if statement to have the rule where if a set variable equals "view-##" where the # signifies any number. what would be the correct syntax for setting up an if statement with that condition?

我正在尝试获取一个 php if 语句来设置规则,其中如果设置变量等于“view-##”,其中 # 表示任何数字。使用该条件设置 if 语句的正确语法是什么?

if($variable == <<regular expression>>){
    $variable2 = 1;
}
else{
    $variable2 = 2;
}

回答by Spudley

Use the preg_match()function:

使用preg_match()函数:

if(preg_match("/^view-\d\d$/",$variable)) { .... }

[EDIT] OP asks additionally if he can isolate the numbers.

[编辑] OP另外询问他是否可以隔离数字。

In this case, you need to (a) put brackets around the digits in the regex, and (b) add a third parameter to preg_match().

在这种情况下,您需要 (a) 在正则表达式中的数字周围加上括号,并且 (b) 将第三个参数添加到preg_match().

The third parameter returns the matches found by the regex. It will return an array of matches: element zero of the array will be the whole matched string (in your case, the same as the input), the remaining elements of the array will match any sets of brackets in the expression. Therefore $matches[1]will be your two digits:

第三个参数返回正则表达式找到的匹配项。它将返回一个匹配数组:数组的元素零将是整个匹配的字符串(在您的情况下,与输入相同),数组的其余元素将匹配表达式中的任何括号集。因此$matches[1]将是您的两位数字:

if(preg_match("/^view-(\d\d)$/",$variable,$matches)) {
     $result = $matches[1];
}

回答by Yet Another Geek

You should use preg_match. Example:

您应该使用preg_match。例子:

if(preg_match(<<regular expression>>, $variable))
{
 $variable1 = 1;
}
else
{
  $variable2 = 2;
}

Also consider the ternary operatorif you are only doing an assignment:

如果您只是在进行赋值,还可以考虑三元运算符

$variable2 = preg_match(<<regular expression>>, $variable) ? 1 : 2;