Search and replace all image files in HTML document

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Charles Bronte

    #1

    Search and replace all image files in HTML document

    Hey there;

    I'm working on creating a Wordpress plugin, but it turns out that my Regular Expressions-fu is lacking.

    How can you replace all image files (jpg, gif, jpeg)?

    I'm thinking a function with the following

    - Receive HTML in a string

    - Only replace image urls starting with http://example.com

    - Replace the domain with http://example2.com

    - Return HTML with image URLs replaced.


    ... But I can't for the life of me create a well-formed piece of code that does this for me.

    Any ideas?
  • kovik
    Recognized Expert Top Contributor
    • Jun 2007
    • 1044

    #2
    Well, I'm assuming by "image files", you mean <img> tags. Basically, you want to search for those tags and make your replacement. Since you've shown that the example that you want to replace is http://example.com to http://example2.com, I can give you a nice little snippet to get you started.

    Code:
    function replace_images($text) {
      /** Regex Parts:
       * \1 is the img tag up to the starting quotation mark
       *    around the file name
       * \2 is the quotation mark
       * \3 is the file name without the domain name
       * \4 is the img tag after the ending quotation mark
       *    around the file name
       */
      $current_domain = 'http://example.com/';
      $target_domain= 'http://example2.com/';
      $img_tag_regex = "(<img[^>]+src=)([\"'])$current_domain([^\2]+?)\2([^>]*>)";
      return preg_replace("~$img_tag_regex~s", "\\1\\2$target_domain\\3\\2\\4", $text);
    }
    Untested, btw. Since you are doing this in WordPress, you'll probably want to set thus function up as a filter.

    Comment

    Working...