preg_replace question

<img src="abc.jpg">

I want to replace abc.jpg with ./abc.jpg, so that <img src="./abc.jpg">

Notes

1) image file may start with digit, eg:123.jpg

2) src does not always follow img, eg: <img width="125" src="abc.jpg" height="456">

Any idea on how to do it?

Thanks,
LVL 1
tiger0516Asked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
hernst42Connect With a Mentor Commented:
Try:
$text = preg_replace('/src="([^"]+)"/i', 'src="./\1"', $text)
0
 
BrianGEFF719Commented:
hrenst42's suggestion is exactly what you've requested, but I'll point out additional things:

 1) If you only want to match images that don't start with ./ already then you need to do: /src="[^./]+([^"]+)"/i
 2) You should really use $1 as it is preferred to \1.


$text = preg_replace('/src="[^./]+([^"]+)"/i', 'src="./$1"', $text)
0
 
tiger0516Author Commented:
Hi hernst42,

Thank you!

Yours works well!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.