简体   繁体   English

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

[英]using regular expressions in if statement conditions

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. 我试图获得一个php if语句,如果一个set变量等于“view - ##”,其中#表示任何数字。 what would be the correct syntax for setting up an if statement with that condition? 设置具有该条件的if语句的正确语法是什么?

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

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];
}

You should use preg_match . 你应该使用preg_match Example: 例:

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

Also consider the ternary operator if you are only doing an assignment: 如果您只做一项任务,还要考虑三元运算符

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM