0
<a href="http://www.example.com/foo/bar/" title="foo">
    <img src="http://www.example.com/foo/bar/" alt="foo" />
</a>

How can I preg_replace the word foo only in the href attribute?

NOTE: There are multiple links on the page.

1 Answer 1

1

You could do this:

$str = preg_replace('/(href="[^"]*)foo/', '$1replacement', $str);

Alternatively, you could use a lookbehind:

$str = preg_replace('/(?<=href="[^"]*)foo/', 'replacement', $str);

Note that this will only work if there are no '-delimited attributes and no escaped " within your attributes.

This is why you should really consider to use a DOM parser, instead of manipulating HTML with regular expressions.

Update: Here is a proper implementation using a parser (I just picked PHP Simple HTML DOM Parser, because it was the first one showing up on Google):

require "simple_html_dom.php";

$html = file_get_html($filename);
foreach($html->find('a') as $element)
{
    $element->href = preg_replace('/foo/', 'replacement', $element->href);
}

Now echoing $html or saving it to a file, will contain the correctly replaced HTML. (Using a DOM parser can be so easy.) ;)

Sign up to request clarification or add additional context in comments.

4 Comments

or, better yet, generating the correct HTML from the very start.
Well who says, the OP is generating it?
any other plausible use-case of transforming an HTML into HTML?
I usually try not to second-guess all possible uses someone might have in mind for a particular question ^^

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.