PDA

View Full Version : Calling functions from within preg_replace() 'PHP'


rich w
July 30th, 2007, 12:38
Ok got a simple one today...


$find = '#<a href="mailto:([^"]+)">([^"]+)</a>#i';
$replacement = "<img src=\"emails/".create_email(strip_tags($2),$p)."\" />";
$remote_page = preg_replace($find,$replacement,$remote_page); //Convert email addresses to images
The bit that is causing all the problems is:

create_email(strip_tags($2),$p)
It's calling the function create_email(), but it's not passing the value of $2. The variable $2 is produced by the preg_replace function, in this case, an email address.

Does anyone know how to make it pass the $2?

Cheers,

inimino
July 30th, 2007, 13:02
create_email() is being called when $replacement is assigned (on the second line) so $2 doesn't exist yet.

You can use preg_replace_callback() with a callback function to do what you want.

rich w
July 30th, 2007, 13:16
Aha never knew about that function. Thanks very much, it works perfectly now :D