<a href="http://www.example.com/foo/bar/" title="bar">Example</a>
How can I replace “bar” only in the href attribute?
Thank you!
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.
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.
Some explanation for the regex:
I start with a capturing group that ensures we are inside the
hrefattribute of ana-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 thehrefattribute to come first, but not for the attribute to close. Then we havebar. And then we add some more stuff before closing the attribute and then the tag.The replacement then simply uses captured groups
$1and$2(which contain everything aroundbar, which we had to use to make sure it’s in the right place) but inserts the new string in between (wherebarused to be).Note, this will especially break if you have attributes containing
>before thehref-attribute!