简体   繁体   中英

Variable inside regular expression php

I a stuck with regular expression and i need help. So basically i want to do somethning like this:

$data = "hi";
$number = 4;

$reg = '/^[a-z"]{1,4}$/';


if(preg_match($reg,$data)) {
    echo 'Match';   
}else {
    echo 'No match';
}

But i want to use variable

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

I have tried:

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

$reg = "/^[a-z\"]{1, $number}$/";

But not getting right result.

Tnx for help

In the first example you have space where you shouldn't have one,

you have:

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

your should have:

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

then it works just fine

Update: You have same error in second example - thanks to AbraCadaver

Another way to use variables in regex is through the use of sprintf.

For example:

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

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