Regular expression for img tag

Discussion in 'PHP' started by greatlogix, Oct 21, 2008.

  1. #1
    I want to change image name in img tag using reg exp.

    <img src="images/abc.jpg" alt="" border="0" align="left">
    HTML:
    Is it possible using reg exp?
     
    greatlogix, Oct 21, 2008 IP
  2. ads2help

    ads2help Peon

    Messages:
    2,142
    Likes Received:
    67
    Best Answers:
    1
    Trophy Points:
    0
    #2
    more details? image name is the src="" or?
     
    ads2help, Oct 21, 2008 IP
  3. greatlogix

    greatlogix Active Member

    Messages:
    664
    Likes Received:
    13
    Best Answers:
    1
    Trophy Points:
    85
    #3
    yes src. i want to change src attribute of image tag
     
    greatlogix, Oct 21, 2008 IP
  4. bartolay13

    bartolay13 Active Member

    Messages:
    735
    Likes Received:
    14
    Best Answers:
    1
    Trophy Points:
    98
    #4
    what is reg exp?
    i know exp = exponent, etc.. but reg exp?
    dont think that there had a predefined function called reg
    can you please explain more?? more detailed.
     
    bartolay13, Oct 21, 2008 IP
  5. greatlogix

    greatlogix Active Member

    Messages:
    664
    Likes Received:
    13
    Best Answers:
    1
    Trophy Points:
    85
    #5
    reg exp=Regular expression

    Any solution?
     
    greatlogix, Oct 21, 2008 IP
  6. shallowink

    shallowink Well-Known Member

    Messages:
    1,218
    Likes Received:
    64
    Best Answers:
    2
    Trophy Points:
    150
    #6
    Yes, it is possible. Is the img tag in its own variable or part of a larger chunk ?
     
    shallowink, Oct 21, 2008 IP
  7. greatlogix

    greatlogix Active Member

    Messages:
    664
    Likes Received:
    13
    Best Answers:
    1
    Trophy Points:
    85
    #7
    part of a larger chunk. A string returned from file_get_contents.

    How it is possible? Any code sample?
     
    greatlogix, Oct 21, 2008 IP
  8. shallowink

    shallowink Well-Known Member

    Messages:
    1,218
    Likes Received:
    64
    Best Answers:
    2
    Trophy Points:
    150
    #8
    I don't have the code to replace the src, I do have the code to first get the actual image tag (which I pulled from another site yesterday) So we can try it first. It may not be correct though.


    preg_match_all('/<img[^>]*>/Ui', $content, $matches);

    Ok, that worked to get the img tag itself. I'm sure there's a better way to do this but this did work ...

    
    $content = 'This is a test. <img src="images/foo.jpg" title="foo">';
    
    $res = preg_match_all('/<img[^>]*>/Ui', $content, $matches);
    
    $string =  $matches[0][0];
    $replacement = 'src="images/bar.jpg"';
    $pattern = '/src=\"\S*\"/Ui';
    
    echo preg_replace($pattern, $replacement, $string);
    
    PHP:
     
    shallowink, Oct 21, 2008 IP