简体   繁体   中英

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 setting 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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