Forum Home
Press F1
 
Thread ID: 108493 2010-03-31 04:09:00 PHP preg_replace setting variables Mike (15) Press F1
Post ID Timestamp Content User
871270 2010-03-31 04:09:00 Is it possible to set a variable using preg_replace in PHP?

So whenever 'whatever' is found set $variable = 1 and replace the 'whatever' with 'blah'... or something to that effect

preg_replace("/whatever/e","$variable = 1; echo 'blah';",$text);

I know the 'e' flag lets you use a php variable as replace string, however it won't let you run PHP code... or will it? Is there a better way to do what I'm wanting?

What I'm really wanting is to stop other preg_replace from happening if $variable = 1, so I'd put those into an if $variable == 0 etc. and when another condition is satisfied the $variable is set back to 0 so the other $preg_replace can run. These are all run within a while loop :)

I'm not sure even I understand what I just wrote :)

Cheers,
Mike.
Mike (15)
871271 2010-03-31 04:22:00 I know the 'e' flag lets you use a php variable as replace string, however it won't let you run PHP code... or will it?That's the entire point of the 'e' flag - it will ;).


Is there a better way to do what I'm wanting?If you've correctly described your problem, it sounds like preg_replace_callback would be a smarter solution. Is there any reason why you can't use that?
Erayd (23)
871272 2010-03-31 04:55:00 That's the entire point of the 'e' flag - it will ;)doesn't seem to let me... what am I doing wrong? For example
$variable = 0
preg_replace("/whatever/e","$variable = 1; echo 'blah';",$text);
seems to return '0 = 1' rather than just set $variable = 1...


If you've correctly described your problem, it sounds like preg_replace_callback would be a smarter solution. Is there any reason why you can't use that?never heard of it :D

Mike.
Mike (15)
871273 2010-03-31 05:14:00 doesn't seem to let me... what am I doing wrong?You're forgetting to escape the '$', and as a result the variable substitution is occurring in the string rather than during the execution phase. Either escape it with a backslash, or use single quotes.


never heard of it :DTake a look here (nz.php.net).
Erayd (23)
871274 2010-03-31 05:46:00 You're forgetting to escape the '$', and as a result the variable substitution is occurring in the string rather than during the execution phase. Either escape it with a backslash, or use single quotes.:D

:D:D:D;)
Mike.
Mike (15)
871275 2010-03-31 05:47:00 Thanks Erayd :)

Mike.
Mike (15)
871276 2010-03-31 05:55:00 Thanks Erayd :)
No problem :D.
Erayd (23)
1