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}/
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