Regular Expression Image without anchor around it

Discussion in 'PHP' started by mark84, Jul 20, 2007.

  1. #1
    The following regular expression matches an image tags with anchor around it,

    preg_match_all ('/((?:<\s*a\s*(?:.*)\s*>)<\s*img\s*(?:.*)\s*\/>(?:<\/\s*a\s*>))/i', $news_text, $pattern1, PREG_PATTERN_ORDER);

    Now i want another expression that matches ONLY the image tags that DOES NOT have anchor tag around it.

    Thanks for any help. :)
     
    mark84, Jul 20, 2007 IP
  2. mark84

    mark84 Peon

    Messages:
    56
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Someone should be able to help.. :(

    let me clarify further...

    For example the following are stored in a variable,

    $str = '<img src="hello.jpg" title="sadsad" />
    <a href="one.html"><img src="hi.jpg" title="asdat" /></a>'

    I want to match ONLY <img src="hello.jpg" title="sadsad" /> not the other.
     
    mark84, Jul 20, 2007 IP
  3. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #3
    Remove this from the beginning: (?:<\s*a\s*(?:.*)\s*>)
    And this from the end: (?:<\/\s*a\s*>)
     
    nico_swd, Jul 20, 2007 IP
  4. mark84

    mark84 Peon

    Messages:
    56
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    That will get me BOTH the images.. but as i mentioned..

    "I want to match ONLY <img src="hello.jpg" title="sadsad" /> NOT the other."

    I will probably have to use the ! operator, but i dont know how to use it properly.
    Tried some didnt work.
     
    mark84, Jul 20, 2007 IP
  5. DavidAusman

    DavidAusman Well-Known Member

    Messages:
    399
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    108
    #5
    The pattern is a bit too lengthy ;), here is the shorter one. This will match whatever in imagesource and alt text.
    
    preg_match("/<a\s*href=[^>]+\s*><img src='([^>]+)' alt='([^>]+)'><\/a>/i", $str, $match);
    
    /**
     *Match[0] will bring you complete link with the image
     *Match[1] gets you img src
     *Match[2] gets you alt title
     */
    
    PHP:
    The code above will match <a href='http://yahoo.com'><img src='yahoo.gif' alt='blabla'></a>

    But if you need to match more anchor pattern, you have to consider properties like title, class, id within the anchor tags. So you will need
    
    preg_match("/<a\s*[^>]+\s*href=[^>]+\s*[^>]+><img src='([^>]+)' alt='([^>]+)'><\/a>/i", 
    $str, 
    $match);
    
    PHP:
    **There's no need for you to add (..) within the anchor tags because you don't actually wants it to be in your array. Unless you want to get the match result just like the img src and alt, then you should use (..)
     
    DavidAusman, Jul 20, 2007 IP