Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 822
EstSiim Avatar asked Sep 12 '14 17:09

EstSiim


2 Answers

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

like image 156
Drecker Avatar answered Oct 29 '22 00:10

Drecker


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}/
like image 40
cbernard73 Avatar answered Oct 29 '22 02:10

cbernard73