REGEX match URL in link ignore other tags?

I was using this regex to extract URL from link:

<a href=\"([^\"]*)\">

Works great but now that I added title to the link it doesn’t works any more.

<a title="Online dating in España" href="">Online dating España</a>

How to make it work as before and simply ignore title=“” stuff?

<a .*?href=\"([^\"]*)\"> should do the trick

Thanks buddy!

How can I grab anchor text from these URLs and add them as title=“” attribute to those links?

$question = '<a href="">Calle Puerto Rico</a>, <a href="">Huelva</a>, <a href="">Andalucía</a>';

I use this but it only matches one link not all:

preg_match('#<a[^>]*>([^<]*)<\/a>#i', $question, $matches);

$link_with_title = str_replace('<a ', '<a title="Online dating in '.$matches['1'].'" ', $matches['0']);

Sounds to me like you’re looking for the preg_replace function :wink:

I am trying for the past 3 hours and can’t find a way please could you help?

Have you looked at preg_replace in the php manual? How far you’ve gotten already applying preg_replace shouldn’t be much of a leap.

But how do I grab anchor text and then add a title=“anchor text” to the link thats what I have no clue?

Can you show the code you’ve tried using preg_replace?

It might be easer to use PHP’s DOM classes to read the HTML, as that automatically does the parsing you try to achieve with a RegExp.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.