<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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You could do this:
Alternatively, you could use a lookbehind:
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):
Now
echoing$htmlor saving it to a file, will contain the correctly replaced HTML. (Using a DOM parser can be so easy.) 😉