Comme je l'ai dit, si vous êtes ok avec quelques erreurs et/ou ont une certaine quantité de contrôle sur l'entrée, vous pouvez faire quelques compromis dans l'exhaustivité et utiliser Regex. Étant donné que votre mise à jour indique que c'est le cas, voici une expression rationnelle qui devrait fonctionner pour vous:
/<a\s(?:.(?!=href))*?href="([^"]*)"[^>]*?>(.*?)</a>/gi
- $: Le HREF
- $: Tout dans la balise.
Cela gérer tous les cas de test ci-dessous, sauf les trois dernières lignes:
Hello this is some text <a href="/test">This is a link</a> and this is some more text.
<a href="/test">Just a link on this line.</a>
There are <a href="/test">two links </a> on <a href="http://www.google.com">this line</a>!
Now we need to test some <a href="http://www.google.com" class="test">other attributes.</a>. They can be <a class="test" href="http://www.google.com">before</a> or after.
Or they can be <a rel="nofollow" href="http://www.google.com" class="myclass">both</a>
Also we need to deal with <a href="/test" class="myclass" style=""><span class="something">Nested tags and empty attributes</span></a>.
Make sure that we don't do anything with <a name="marker">anchors with no href</a>
Make sure we skip other <address href="/test">tags that start with a even if they are closed with an a</a>
Lastly try some other <a href="#">types</a> of <a href="">href</a> attributes.
Also we need to skip <a malformed tags. </a>. But <a href="#">this</a> is where regex fails us.
We will also fail if the user has used <a href='javascript:alert("the reason"))'>single quotes for some reason</a>
Other invalid HTML such as <a href="/link1" href="/link2">links with two hrefs</a> will have problems for obvious reasons.
Si vous devez manipuler HTML, ne pas utiliser une expression régulière. –
Pouvez-vous être certain que ce qui se passe en tant qu'argument est juste un ou y aura-t-il d'autres bits? – Layke
Trop ambigu. Quelle langue, environnement? –