# Modify Image Source With The_Content Filter?

I'm very inexperienced with regex, however I'm trying to create a function that filters through the_content() and get_the_content() in order to modify the SRC of all images. The intended purpose would be to modify the URL's to use http://i0.wp.com/ instead of http://. This would allow posts to utilize the Photon API without needing the JS side of Photon..

I know I need to hook into the_content() using a filter in order to accomplish this, but I was unable to accoplish this using str_replace(), so I'm assuming using preg_replace() would work.

Also, if it's possible to add ?quality=70&strip=all to the end of the URL this would help decrease page speed.

Any thoughts?

• That wouldn't work, because I'm referring to images that are already in the_content, I'm not running that function myself... – Austin Biggs Nov 6 '15 at 13:22
• Try regexbuddy to write your regex. Yes you need regex for this. – Firsh - LetsWP.io Nov 6 '15 at 13:30
• I would say "use the Javascript". regex on markup is very tricky and very error prone. – s_ha_dum Nov 6 '15 at 14:47
• I'm not looking to use JavaScript, I'm looking to use PHP – Austin Biggs Nov 6 '15 at 21:35

$str = '<img src="http://myserver.mydomain/picture.png" />';$pattern ='#<img src="http://.*/(.*)" />#';
$replace = '<img src="http://http://i0.wp.com/$1?quality=70&strip=all />"';
$result = preg_replace($pattern, $replace,$str);

The $pattern is quite simple and very specific. You might need to generalize it a bit more but it should show you the direction to go. E.g. it takes no care of possible whitespace. A first attempt to take care of this: $pattern ='#<\s*img\s*src\s*=\s*"http://myserver.mydomain/(.*)"\s*/\s*>#';