Forum Moderators: coopster

Message Too Old, No Replies

Inserting a variable into a regexp pattern

         

stormshield

2:25 pm on Apr 30, 2009 (gmt 0)

10+ Year Member



Hello,

preg_match_all('/thing/s',$text,$out,PREG_SET_ORDER);

This will find all occurences of "thing" in $text.


$thing = "thing";

preg_match_all('/' . $thing . '/s',$text,$out,PREG_SET_ORDER);

Why doesn't this work?

stormshield

2:58 pm on Apr 30, 2009 (gmt 0)

10+ Year Member



I'm sorry I got it all wrong... the real cause of problems was the whitespace in front of the variable $thing (I passed the variable as a function argument). It works now :]

d40sithui

3:02 pm on Apr 30, 2009 (gmt 0)

10+ Year Member



it's funny how many people are able to solve their own problems after posting on webmasterworld haha

rocknbil

3:28 pm on Apr 30, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



There's actually a better way than that. What if you want to add modifiers, etc? Compile your entire regexp in the variable.

$thing = '/^\s*thing\s*$/im';
// Case-insensitive, treat as multiple lines, starts
// and ends with exactly "thing" and zero or more
// spaces before or after

preg_match_all("$thing",$text,$out,PREG_SET_ORDER);