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; }
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.
The ?! n quantifier matches any string that is not followed by a specific string n.
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]; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With