Simple RegEx PHP

Since I am completely useless in regex, and it has been listening to me for the last half hour, I think I will post it here, as it is probably pretty 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 something from the sample tags <a>:

hey.exe
hey2.dll
pomp.jpg
+3
source share
5 answers

Avoid using ". *" Even if you make it jagged until you have more practice with RegEx. I think that would be a good solution for you:

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

Pay attention to the delimiters '/' - you should use a preg-set of regular expression functions in PHP. It will 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);
+6
source

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

+2
source

, .

+2

:

<a.*>(.*)</a>

, , .

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

:

<a.*?>(.*?)</a>

Pay attention to '?' after the quantifier '*'. By default, quantifiers are greedy, which means that they eat as many characters as they can (which means that in this example they will only return "hey2.dll"). By adding quotes, you make them jagged, which should suit your needs.

+2
source

It works:

$pattern = '/<a.*?>(.*?)<\/a>/';
+2
source

Source: https://habr.com/ru/post/1703910/


All Articles