Azhar Azhar - 2 months ago 7
PHP Question

Find all possible file links in a string and set a download button with a link of them inside

I wanna change the code below to get all possible files with all possible extensions and not just exe,zip,rar,bin etc.

$find=array('~(<a(.*)href="([^"]*.exe)"(.*)>)([^<]*)(</a>)~',
'~(<a(.*)href="([^"]*.zip)"(.*)>)([^<]*)(</a>)~',
'~(<a(.*)href="([^"]*.rar)"(.*)>)([^<]*)(</a>)~',
'~(<a(.*)href="([^"]*.bin)"(.*)>)([^<]*)(</a>)~');


$matches[$i][1] = preg_replace($find, '<p>$0</p><a href=$3 class="btn btn-success" download>Download</a>',$matches[$i][1]);

Answer

I could give you some simple example that you can apply to you work

<a href="(?:\.\/)?(?:[^\/"]+\/)*[^\/"]*\.([a-zA-Z]+)">

This regex will try to capture file extension in the open <a ...> tag.

Explanation

(?:\.\/)? match a prefix ./ of file path if it exists,

(?:[^\/"]+\/)* match any possible paths that end with / e.g. this/is/my/path/,

[^\/"]* match a file name,

\. match a dot,

([a-zA-Z]+) match a file extension.

See DEMO