开发者

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. what would be the correct syntax for s开发者_开发百科etting up an if statement with that condition?

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


Use the preg_match() function:

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

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

In this case, you need to (a) put brackets around the digits in the regex, and (b) add a third parameter to 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:

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


You should use 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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜