Как я уже говорил ранее, если вы в порядке с некоторыми ошибками и / или имеете некоторый контроль над вводом, вы можете пойти на некоторые компромиссы в полноте и использовать Regex. Поскольку в вашем обновлении говорится, что это так, вот регулярное выражение, которое должно работать для вас:
/<a\s(?:.(?!=href))*?href="([^"]*)"[^>]*?>(.*?)</a>/gi
- $ 1 : HREF
- $ 2 : все, что находится внутри тега.
Это будет обрабатывать все тестовые примеры, кроме последних трех строк:
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.