2

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?

5
  • 2
    Use html parser instead Commented Jan 8, 2019 at 13:10
  • i have to use regex Commented Jan 8, 2019 at 13:12
  • 1
    Why do you have to use regex? Homework? Commented Jan 8, 2019 at 13:14
  • yes i want to change src to data-src Commented Jan 8, 2019 at 13:25
  • 1
    @JiříKaštovský It works - regex101.com/r/mwvphb/1 Commented Jan 8, 2019 at 13:32

1 Answer 1

2

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).

Sign up to request clarification or add additional context in comments.

1 Comment

it is only replace the first match,, how to replace in multiple tags?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.