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.

user557108
  • 1,195
  • 3
  • 17
  • 26

1 Answers1

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.) ;)

Community
  • 1
  • 1
Martin Ender
  • 43,427
  • 11
  • 90
  • 130