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... Nov 6, 2015 at 13:22
  • 1
    Try regexbuddy to write your regex. Yes you need regex for this. Nov 6, 2015 at 13:30
  • 1
    I would say "use the Javascript". regex on markup is very tricky and very error prone.
    – s_ha_dum
    Nov 6, 2015 at 14:47
  • I'm not looking to use JavaScript, I'm looking to use PHP Nov 6, 2015 at 21:35

1 Answer 1


Let's give it a try:

$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*>#';
  • This looks great, I actually need to remove the URL protocol from the original source when creating the new source link. So I'll take a look at this and work it from there, thanks! Nov 9, 2015 at 17:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.