9

I'm trying to replace all link href's in a large string with a different URL. With the following code It seems to replace only the 2nd link leaving the first one intact, can someone help me out?

$string_of_text = '<a href="http://www.php.net/">PHP</a> <a href="http://www.apache.org/">Apache</a>';
echo preg_replace('/<a(.*)href="(.*)"(.*)>/','<a$1href="javascript:alert(\'Test\');"$3>',$string_of_text);
3
  • 1
    Please fix your question title to describe the question. Take a look at all the rubbish in the "Related" pane on the right of my comment, and don't add to it. :) Commented Jan 30, 2012 at 0:40
  • 1
    It might be easier to use an HTML parser. Commented Jan 30, 2012 at 0:40
  • 1
    Lol, I'm sorry Lightness Races in Orbit, I can't see an edit button anywhere however I'll be sure my next question is much more detailed Commented Jan 30, 2012 at 0:45

3 Answers 3

16

Instead of any char . use any not (^) quote [^"]

echo preg_replace('/<a(.*)href="([^"]*)"(.*)>/','<a$1href="javascript:alert(\'Test\');"$3>',$string_of_text);
Sign up to request clarification or add additional context in comments.

2 Comments

@JoopEggen , i have nearly similar problem. i have an array of links containing id params, and another array of ids. i want to replace all link's href attribute of the first array that have the same ids in the second array.... sorry for my grammar, if incorrect!!!
@user8009 (no sorry neeeded - hey, I am esperantist: English = gcd, Esperanto = lcm) Maybe put a question in SO with some more details. There exists a regex replace applying a function for replacement: php.net/manual/en/function.preg-replace-callback.php maybe that could be used in your case.
6

Just use the greedy operator in your regex like this:

'/<a(.*?)href="(.*?)"(.*?)>/'

Comments

0

Slight modifications to Aurelio De Rosa's answer:

'/<a(.*?)href=(["\'])(.*?)\\2(.*?)>/i'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.