Variable inside php regex

I am stuck with regex and I need help. So basically I want to do something like this:

$data = "hi"; $number = 4; $reg = '/^[az"]{1,4}$/'; if(preg_match($reg,$data)) { echo 'Match'; }else { echo 'No match'; } 

But I want to use a variable

 $reg = '/^[az"]{1, variable here }$/'; 

I tried:

 $reg = '/^[az"]{1, '. $number .'}$/'; $reg = "/^[az\"]{1, $number}$/"; 

But the correct result does not work.

Tnx for reference

+5
source share
2 answers

In the first example, you have a place where you should not have it,

you have:

 $reg = '/^[az"]{1, '. $number .'}$/'; 

you should have:

 $reg = '/^[az"]{1,'. $number .'}$/'; 

then it works just fine

Update: in the second example there is the same error - thanks to AbraCadaver

+14
source

Another way to use variables in regex is to use sprintf.

For instance:

 $nonWhiteSpace = "^\s"; $pattern = sprintf("/[%s]{1,10}/",$nonWhiteSpace); var_dump($pattern); //gives you /[^\s]{1,10}/ 
+1
source

Source: https://habr.com/ru/post/1202440/


All Articles