Change img scr path but not filename in a post body

Discussion in 'PHP' started by mnymkr, Feb 19, 2011.

  1. #1
    I need to change the src path (not necessarily http:) for all img in a blog post body.

    I prefer to use preg match / replace if possible

    For example:

    <img src="b.image.com/kittykat.png" />
    
    would become
    <img src="/images/kittykat.png" />
    Code (markup):

     
    mnymkr, Feb 19, 2011 IP
  2. tvoodoo

    tvoodoo Active Member

    Messages:
    239
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    53
    #2
    
    $string = ' <img src="b.image.com/kittykat.png" />';
    preg_match_all('/(src)=("[^"]*")/i',$string,$matches);
    
    $src = explode("/",$matches[2][0]);
    echo '<img src="/images/'.$src[1].'" />';
    
    PHP:
     
    tvoodoo, Feb 19, 2011 IP
  3. Alex Roxon

    Alex Roxon Active Member

    Messages:
    424
    Likes Received:
    11
    Best Answers:
    7
    Trophy Points:
    80
    #3
    Or you could just get it in one go:
    $string = ' <img src="b.image.com/src/kittykat.png" />';
    preg_match('/src\=[\"\\\']{0,1}.*?\/([a-zA-Z0-9\_\-\+\s]+\.[a-zA-Z]+)[\"\\\']/i',$string,$matches);
    //$matches[1] contains the filename
    PHP:
     
    Alex Roxon, Feb 19, 2011 IP
  4. mnymkr

    mnymkr Well-Known Member

    Messages:
    2,328
    Likes Received:
    32
    Best Answers:
    0
    Trophy Points:
    120
    #4
    This definitely works but I can't see how to use it to modify my database fields (the posts).

    I think I need to match everything before the filename not the filename so I can you preg_replace

    right?
     
    mnymkr, Feb 20, 2011 IP