Results 1 to 4 of 4

Thread: Regex Help

  1. #1
    Join Date
    Jan 2008
    Posts
    51
    Thanks
    46
    Thanked 1 Time in 1 Post

    Default Regex Help

    Hello everyone,

    Say I have a string like this:

    PHP Code:
    $string "This is a apple. <img src=\"apple.jpg\" /> This is a banana. <img src=\"banana.jpg\" />"
    How would I go about extracting only the <img src="\apple.jpg\" />. Basically, how would I extract the first <img> tag that exists within a given string.

  2. #2
    Join Date
    Jun 2007
    Posts
    543
    Thanks
    3
    Thanked 78 Times in 78 Posts
    Blog Entries
    1

    Default

    only the first:
    PHP Code:
    preg_match('/<img src=\\"[a-z0-9]{1,20}[.](jpg|jpeg|gif|png)\\"[ ]?(alt=\\"[a-z0-9]\\")?[ ]?[/]?>/i'$string$img); 
    $img[0] will contain the first img tag
    Edit: Look at updated version below
    Last edited by Master_script_maker; 03-24-2008 at 03:04 PM.
    [Jasme Library (Javascript Motion Effects)] My Site
    /\/\@§†ê® §©®¡þ† /\/\@|{ê®
    There are 10 kinds of people in the world, those that understand binary and those that don't.

  3. #3
    Join Date
    Jul 2006
    Location
    just north of Boston, MA
    Posts
    1,806
    Thanks
    13
    Thanked 72 Times in 72 Posts

    Default

    Quote Originally Posted by Master_script_maker View Post
    only the first:
    PHP Code:
    preg_match('/<img src=\\"[a-z0-9]{1,20}[.](jpg|jpeg|gif|png)\\"[ ]?(alt=\\"[a-z0-9]\\")?[ ]?[/]?>/i'$string$img); 
    $img[0] will contain the first img tag
    that doesn't allow for other image tag attributes. like title, width,height being the most probable ones to appear

  4. #4
    Join Date
    Jun 2007
    Posts
    543
    Thanks
    3
    Thanked 78 Times in 78 Posts
    Blog Entries
    1

    Default

    Quote Originally Posted by boogyman View Post
    that doesn't allow for other image tag attributes. like title, width,height being the most probable ones to appear
    updated version :
    PHP Code:
    preg_match('/<img src=\\"[a-z0-9]{1,20}[.](jpg|jpeg|gif|png)\\"[ ]?(alt=\\"[a-z0-9]\\"[ ]?|title=\\"[a-z0-9]\\"[ ]?|width=\\"[0-9]\\"[ ]?|height=\\"[0-9]\\"[ ]?)*[/]?>/i'$string$img); 
    [Jasme Library (Javascript Motion Effects)] My Site
    /\/\@§†ê® §©®¡þ† /\/\@|{ê®
    There are 10 kinds of people in the world, those that understand binary and those that don't.

  5. The Following User Says Thank You to Master_script_maker For This Useful Post:

    ReadyToLearn (05-05-2008)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •