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:
- there might be any number of occurances (zero, one, multiple),
- I want to change only those from https://static.example.com/gallery/ and not from https://example.com nor https://static.example.com
- I dont want to parse it as DOM, because it is so slow for my purpose.
Thank you.
Advertisement
Answer
How about something simple like:
(?<='https://static.example.com/gallery/)(.*?)(..*?)(?=')
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
.