Reputation: 1215
<a href="http://www.example.com/foo/bar/" title="bar">Example</a>
How can I replace "bar" only in the href attribute?
Thank you!
Upvotes: 0
Views: 1798
Reputation: 40582
Something like this will work, but the exact approach you would want to take really depends on whether you want to do this case-insensitive, for a specific link, or for all links in a page (i.e. globally) and the goal of your replace.
$var = preg_replace('@<a href=(["\'])(.*)/bar/["\']@', "<a href=\\1\\2/foo/\\1", '<a href="http://www.example.com/foo/bar/" title="bar">Example</a>');
Upvotes: 0
Reputation: 44259
Let me start off by saying, regular expressions are not the right tool. (At least not to find the attributes; for the replacement, probably...)
However, here is a regular expression solution anyway, but I cannot guarantee that it will work on all valid DOMs.
$newStr = preg_replace(
'/(<a\s+[^>]*href="[^"]*)bar([^"]*"[^>]*>)/',
'$1newString$2',
$str);
Some explanation for the regex:
I start with a capturing group that ensures we are inside the href
attribute of an a
-Tag. The reason we capture this is, that it makes the replacement a bit cleaner. The \s+[^>]*
allows for other attributes to come first, but not for the tag to close. The [^"]
allows for more content in the href
attribute to come first, but not for the attribute to close. Then we have bar
. And then we add some more stuff before closing the attribute and then the tag.
The replacement then simply uses captured groups $1
and $2
(which contain everything around bar
, which we had to use to make sure it's in the right place) but inserts the new string in between (where bar
used to be).
Note, this will especially break if you have attributes containing >
before the href
-attribute!
Upvotes: 3