PDA

View Full Version : PHP preg_replace setting variables



Mike
31-03-2010, 05:09 PM
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.

Erayd
31-03-2010, 05:22 PM
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?

Mike
31-03-2010, 05:55 PM
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.

Erayd
31-03-2010, 06:14 PM
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 (http://nz.php.net/manual/en/function.preg-replace-callback.php).

Mike
31-03-2010, 06:46 PM
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
31-03-2010, 06:47 PM
Thanks Erayd :)

Mike.

Erayd
31-03-2010, 06:55 PM
Thanks Erayd :)
No problem :D.