16

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

3
  • 1
    In the first example, you are using single quotes which prevents PHP from parsing your variable as a variable. Commented Sep 12, 2014 at 17:54
  • 3
    @AlexW - it doesn't matter which quotes did he use, since he split the string to two parts and add $number via . operator Commented Sep 12, 2014 at 18:00
  • 1
    @Drecker I was referring to the example above that. Where he put variable here. Commented Sep 12, 2014 at 18:01

2 Answers 2

40

In the first example you have an extra space where you shouldn't have one.

Also, you should always quote such variable as it may contain special characters recognized by regex. You should have:

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

then it would work just fine.

Sign up to request clarification or add additional context in comments.

1 Comment

I had a problem with this where when I tried putting variables inside it, it doesn't work but when I put in the text from the variable to the correct location, it works quite find.
4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.