Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get text from all <a> tags in string

Since I am completely useless at regex and this has been bugging me for the past half an hour, I think I'll post this up here as it's probably quite simple.

<a href="/folder/files/hey/">hey.exe</a>
<a href="/folder/files/hey2/">hey2.dll</a>
<a href="/folder/files/pomp/">pomp.jpg</a>

In PHP I need to extract what's between the <a> tags example:

hey.exe
hey2.dll
pomp.jpg
like image 702
zuk1 Avatar asked Oct 19 '25 01:10

zuk1


1 Answers

Avoid using '.*' even if you make it ungreedy, until you have some more practice with RegEx. I think a good solution for you would be:

'/<a[^>]+>([^<]+)<\/a>/i'

Note the '/' delimiters - you must use the preg suite of regex functions in PHP. It would look like this:

preg_match_all($pattern, $string, $matches);
// matches get stored in '$matches' variable as an array
// matches in between the <a></a> tags will be in $matches[1]
print_r($matches);
like image 165
robmerica Avatar answered Oct 21 '25 14:10

robmerica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!