Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; } 
like image 633
Alex Getty Avatar asked Jun 17 '11 18:06

Alex Getty


People also ask

Can we use if condition in regular expression?

If-Then-Else Conditionals in Regular Expressions. A special construct (? ifthen|else) allows you to create conditional regular expressions. If the if part evaluates to true, then the regex engine will attempt to match the then part.

What is ?! In regex?

The ?! n quantifier matches any string that is not followed by a specific string n.


1 Answers

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]; } 
like image 67
Spudley Avatar answered Sep 30 '22 09:09

Spudley