1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

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):

    SEMrush
     
    mnymkr, Feb 19, 2011 IP
    SEMrush
  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,329
    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