How to replace src for data-src with regex?

i have whole page in html and before output i want to replace all img src for data-src i am using

  return (preg_replace('~<img[^>]*\K(?=src)~i','data-',$buffer));

but this doesnt match for example

<img alt="alt" src="src">

it only matches when the src is first

<img src="src"

I cant get it to work like i want, can you help me edit this pattern to do what i need?

Upvotes: 2

Views: 1232

Answers (1)

Dominic
Dominic

Reputation: 96

I think this should work for you:

preg_replace("/(<img[^>]*)src=/", "$1data-src=", '<img alt="alt" src="src">');

$1 is a backreference representing the first matched group (everything in the parentheses of the pattern).

Upvotes: 2

Related Questions