Adding variables in regex patterns??

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
welsh_sponger
Forum Newbie
Posts: 14
Joined: Fri Feb 03, 2006 7:46 am

Adding variables in regex patterns??

Post 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
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post 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);
Post Reply