Thread: Preg_replace

    #1
  1. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2008
    Posts
    369
    Rep Power
    55

    Question Preg_replace


    Ok I need to wrap images in a div. I have a chunk of content which will contain text, images, links etc. I need to go through it and take every image found and wrap it in a div. What makes it even more difficult is that some of the images will be links, in which case the link with the image will need to be wrapped in a div.

    Question is, when you use 'or' in a regex replace, is there any way to do it all with one preg_replace() ? In the following code, only the first match will be replaced, in the event it is wrapped by <a>, it becomes $2. Am I missing something? Or do I have to do this in 2 separate preg_replace calls?

    PHP Code:
    $pattern "/(\<img.*?\>)|(\<a.*?\>\<img.*?\>\<\/a\>)/";
    $content preg_replace($pattern"<div class='image'>$1</div>"$content); 
    Thanks for the help.
  2. #2
  3. Transforming Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    14,181
    Rep Power
    9398
    Is this something you can do using JavaScript instead? Like jQuery?

    Untested (because it's almost 1am):
    Code:
    #(<a\s.*?>)?\s*(<img\s.*?>)\s*(?(1)</a>|)#
    Remember that $0 will be the entire substring matched...
  4. #3
  5. kill 9, $$;
    Devshed Supreme Being (6500+ posts)

    Join Date
    Sep 2001
    Location
    Shanghai, An tSín
    Posts
    6,898
    Rep Power
    3887
    I would generally advise against using your own regexps for parsing HTML. There are loads of proper HTML parsers out there that will make life much easier in the long run once you've figured out how to use them.

IMN logo majestic logo threadwatch logo seochat tools logo