Preg match and replace for img urls

Discussion in 'PHP' started by ade92uk, Jan 22, 2009.

  1. #1
    I have used preg match to find in a page all img tags:

    <(img)[^>]*?>
    Code (markup):

    Can someone please tell me how i would check if it has a full url and if it does not replace it with a full url from a variable called $link2. I would also like to be able to process urls which have change directory such as: ../images/example.gif --> to http://example.com/images/example.gif using the http://example.com previously stored in $link2.

    I have tried, without any luck:


    if ($urlres = true) {
    						
    						for($i = 0, $size = sizeof($matches[0]); $i < $size; ++$i)
    					{
    					$imgurl =  preg_match_all('#http:\/\/#si', $matches[0][$i], $matches);
    					if ($imgurl = true) {break;} else 
    					preg_replace('#src="#si', '#src="$link2#', $matches[0][$i]);
    					}
    			}
    			
    
    
    
    
    
    Code (markup):

    Thanks
     
    ade92uk, Jan 22, 2009 IP
  2. t3nt3tion

    t3nt3tion Peon

    Messages:
    32
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    I think you need to use $matches[1]
     
    t3nt3tion, Jan 22, 2009 IP
  3. Gangsta

    Gangsta Active Member

    Messages:
    145
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    53
    #3
    if (preg_match_all('/<img[^>]+>/isU', $html, $matches) {

    for($i = 0, $size = sizeof($matches[0]); $i < $size; ++$i) {

    if (preg_match('#http:\/\/#si', $matches[0][$i]) break;
    else preg_replace('#src="#si', 'src="' . $link2 . '#', $matches[0][$i]);
    }
    }
     
    Gangsta, Jan 22, 2009 IP
  4. Gangsta

    Gangsta Active Member

    Messages:
    145
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    53
    #4
    so your problem is that you use $imgurl = preg_match_all('#http:\/\/#si', $matches[0][$i], $matches);

    I mean you already have array $matches so you have to use $matches2 for example
    or use code that I posted above

    btw you may also use str_replace. Sometimes it is faster.
    and also you might be interesting in preg_replace_callback function

    ask any question
     
    Gangsta, Jan 22, 2009 IP