makonix
makonix

Reputation: 9

PHP regex - find and replace link title if the link contains specific string

I am trying to do this regex match and replace, but am not able to do it.

Example

<a href="../files/...">One</a>
<a href"../files/...">Two</a>
<a href="three">Three</a>
<a href="four">Four</a>

I want to find each set of the a tags and replace with something like this

Find each link that contains "/file" string in href

<a href="../files/...">One</a>

and Replace its name to

<a href="../files/...">One (FileType Filesize)</a>

same way the rest of the a tags.

Any help would be very appreciated!

Upvotes: 0

Views: 194

Answers (1)

Andris Leduskrasts
Andris Leduskrasts

Reputation: 1230

(<a href(?=[^>]*\/file)[^<]*)(<\/a>) will find the links you're interested in. Test it here: https://regex101.com/r/tG4fT1/1 . If your desired substitute is static, you can do it with regex and preg_replace alone.

$re = "/(<a href(?=[^>]*\\/file)[^<]*)(<\\/a>)/"; 
$subst = "$1 (Filetype Filesize)$2"; 

$result = preg_replace($re, $subst, $str);

Now, this is assuming you actually want the string (Filetype Filesize) added, not the actual values of Filetype and Filesize, and it's what your question looks to tackle. If it's the values, it gets more complicated and, according to this answer, you might have to use anonymous functions for that, while also specifying the correct match for each value.

Upvotes: 1

Related Questions