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

Ale*_*tty 22 php regex if-statement

我试图获得一个php if语句,如果一个set变量等于"view - ##",其中#表示任何数字.设置具有该条件的if语句的正确语法是什么?

if($variable == <<regular expression>>){
    $variable2 = 1;
}
else{
    $variable2 = 2;
}
Run Code Online (Sandbox Code Playgroud)

Spu*_*ley 38

使用preg_match()功能:

if(preg_match("/^view-\d\d$/",$variable)) { .... }
Run Code Online (Sandbox Code Playgroud)

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

在这种情况下,您需要(a)在正则表达式中的数字周围放置括号,以及(b)添加第三个参数preg_match().

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

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


Yet*_*eek 5

您应该使用preg_match。例子:

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

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

$variable2 = preg_match(<<regular expression>>, $variable) ? 1 : 2;
Run Code Online (Sandbox Code Playgroud)