Page 1 of 1

Adding variables in regex patterns??

Posted: Sun Mar 12, 2006 6:48 am
by welsh_sponger
Is it possible to pass variables into regex patterns?

Ive thought about this...

Code: Select all

$variable = 1234;
    .
    .
    .
preg_match( "#\s\w...\s*"$variable"\s*...#"...)
    .
    .
    .
Would this work, or is there another way?

Thanks

Posted: Sun Mar 12, 2006 7:03 am
by Chris Corbyn
Yes it's possible, but your syntax is wrong there because you closed the string mid-way.

Just build the pattern like any other string:

Code: Select all

$number = 1234;

$regexp = '/\s\w...\s*'.$number.'\s*.../';

preg_match($regexp, $string);