Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 7 of 7
  1. #1
    New Coder
    Join Date
    Jul 2005
    Posts
    54
    Thanks
    2
    Thanked 1 Time in 1 Post

    preg_replace help

    Hello Peeps

    I am not good at all with preg_replace and would hopefully someone can advice.

    How can I strip out a img tag and just get it's alt value ie.

    Replace this:

    <img src="/img/image.gif" alt="This Image" />

    with this

    "This Image"

    I hope this makes sense.

    hope you can advise.

    thanks in advanced if you can.

    Lee

  • #2
    Senior Coder shyam's Avatar
    Join Date
    Jul 2005
    Posts
    1,563
    Thanks
    2
    Thanked 163 Times in 160 Posts
    PHP Code:
    preg_replace('/<img .*?\salt="([^"]+)"[^>]*>/i''$1'
    You never have to change anything you got up in the middle of the night to write. -- Saul Bellow

  • #3
    New Coder
    Join Date
    Jul 2005
    Posts
    54
    Thanks
    2
    Thanked 1 Time in 1 Post
    Thanks for the reply but I cant get it to work.

    Here is my exmaple of yours.

    $1 = '<img src="/img/test.gif" alt="m test" />';

    echo preg_replace('/<img .*?\salt="([^"]+)"[^>]*>/i', '$1');

    Am I doing it wrong ?

    Thanks Again

    Lee

  • #4
    Senior Coder shyam's Avatar
    Join Date
    Jul 2005
    Posts
    1,563
    Thanks
    2
    Thanked 163 Times in 160 Posts
    thats gotta be
    PHP Code:
    $text '<img src="/img/test.gif" alt="m test" />';
    echo 
    preg_replace('/<img .*?\salt="([^"]+)"[^>]*>/i''$1'$text); 
    You never have to change anything you got up in the middle of the night to write. -- Saul Bellow

  • #5
    Senior Coder
    Join Date
    Sep 2005
    Posts
    1,791
    Thanks
    5
    Thanked 36 Times in 35 Posts
    by way of explanation, the '$1' is a reference to the first (in this case only) ()'d bit inside the pattern. The manual page (http://php.net/preg-replace) has more, see the bit on 'replacement' and the first example.
    My thoughts on some things: http://codemeetsmusic.com
    And my scrapbook of cool things: http://gjones.tumblr.com

  • #6
    New Coder
    Join Date
    Jul 2005
    Posts
    54
    Thanks
    2
    Thanked 1 Time in 1 Post
    Thats Fantastic work really well.

    could I ask one more thing. could I add brackets around the name like.

    [img name]

    Just so it makes it easier to see.

    Hope you can advice.

    Thank you very much.

    Regards

    Lee

  • #7
    New Coder
    Join Date
    Jul 2005
    Posts
    54
    Thanks
    2
    Thanked 1 Time in 1 Post
    Dont worry I was being thick.

    Got it working perfect.

    Thank you very much.

    regards

    Lee


  •  

    Posting Permissions

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