Skip to content
Advertisement

PHP change file extension in HTML as plaintext

I want to change file extension in HTML code on PHP output. Probably with regex and this is something I really cannot handle..

...some code...<img data-src='https://static.example.com/gallery/image.jpg'>...some code...

should be changed to

...some code...<img data-src='https://static.example.com/gallery/image.webp'>...some code...

Please note that:

Thank you.

Advertisement

Answer

How about something simple like:

(?<='https://static.example.com/gallery/)(.*?)(..*?)(?=')

As seen here at regex101.com.

Explanation:

We use the regex positive lookbehind in this (?<=) which ensures that the match must be preceded by the site name. If you want the site name to be variable too, that’s a whole ‘nother issue.

As long as the site name is fixed to static.example.com/gallery/, we can just capture the name of the file in the first parentheses (capturing group 1), and the dot+extension in capturing group 2. Then we can just replace this match with the file name (1st capturing group $1) and the new dot+extension .webp.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement