Page 1 of 1

Adding website url to images

Posted: Mon Nov 30, 2009 2:01 am
by Mr Tech
I have the following code below on my website. It's used to find the images in a block of html that don't have http:// or / in front. If this is the case, it will add the website url to the front of the image source.

E.g:

<img src="http://domain.com/image.jpg"> will stay the same
<img src="/image.jpg"> will stay the same
<img src="image.jpg"> will be changed to <img src="http://domain.com/image.jpg">

I feel my code is really inefficient... Any ideas on how I could make it run with less code?

Code: Select all

   preg_match_all('/<img[\s]+[^>]*src\s*=\s*[\"\']?([^\'\" >]+)[\'\" >]/i', $content_text, $matches);
        if (isset($matches[1])) {
            foreach($matches[1] AS $link) {
                if (!preg_match("/^(https?|ftp)\:\/\//sie", $link) && !preg_match("/^\//sie", $link)) {
                    $full_link = get_option('siteurl') . '/' . $link;
                    $content_text = str_replace($link, $full_link, $content_text);
                }
            }
        }

Re: Adding website url to images

Posted: Mon Nov 30, 2009 10:55 am
by AbraCadaver
You can combine all nine lines of code into one preg_replace(). Definitely not tested, but it may get you started. I just combined your patterns using a negative lookbehind:

Code: Select all

$content_text = preg_replace("/<img[\s]+[^>]*src\s*=\s*[\"']?(?<!https?|ftp|\/)([^\"' >]+)[\"' >]/si", $full_link . "/\\1", $content_text);
-Shawn

Re: Adding website url to images

Posted: Mon Nov 30, 2009 5:51 pm
by ridgerunner
AbraCadaver was heading down the right track, but you need to use negative lookahead. (You also need to save the first chunk of the IMG tag so that you can piece it back together with the replace operation.) Here's a solution that does the trick in one whack:

Code: Select all

$content_text = preg_replace('%
    (<img\b[^>]*?src\s*+=\s*+)  # capture first chunk of IMG tag in group 1
    ("|\\'|)                     # capture SRC attribute delimiter in group 2
    (?!\w++://|/)               # ensure URL has no scheme nor abs path
    ([^"\\' >]++)                # capture relative URI path in group 3
    \2                          # match closing delimiter for SRC attribute
    %ix', '$1"http://domain.com/$3"', $content_text);

Re: Adding website url to images

Posted: Mon Nov 30, 2009 5:59 pm
by Mr Tech
Perfect! Just what I needed! Thank you both :)