manipulating preg_replace() variables

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

Moderator: General Moderators

Post Reply
csh
Forum Newbie
Posts: 3
Joined: Mon Sep 10, 2007 12:25 pm

manipulating preg_replace() variables

Post by csh »

Let's say I want to change the href attribute to be an argument of another url for all my <a> elements. For example:

Change:
http://www.old.com

To:
http://www.new.com?url=[b]http//www.old.com[/b]

I need to urlencode the old url, but can't figure out how to do it. If I use:

preg_replace("\<a href='(.*)'(.*)\>", "<a href='http://www.new.com?url=".[b]urlencode("$1")[/b].".'$2>", $content);

Then, I get:

http://www.new.com?url=[b]%241[/b]

Meaning it's not recognizing the variable. Any ideas?

thanks in advance, Chuck
csh
Forum Newbie
Posts: 3
Joined: Mon Sep 10, 2007 12:25 pm

Post by csh »

I think I got it. I think the following works:

preg_replace("/\<a href='(.*)'(.*)\>/e", "'<a href=\'http://www.new.com?url=[b]'[/b].urlencode('$1').'\'$2>'", $content);

(Note that I had forgotten to put the slashes around the regular expression in the first post, but assuming they were put in, it would still have not worked)
User avatar
vigge89
Forum Regular
Posts: 875
Joined: Wed Jul 30, 2003 3:29 am
Location: Sweden

Post by vigge89 »

An alternative is to use preg_replace_callback() together with a nice callback function.
Post Reply