Preg Match remove all <div> tags but keep content

Discussion in 'PHP' started by thankyou, Apr 5, 2012.

  1. #1
    Hi all

    I am trying to remove all <div> tags but keep its content but couldn't.
    Working Example:
    However if:

    I got the </div>

    Another problem:

    I have tried for hours to solve this but couldn't. Need help
     
    thankyou, Apr 5, 2012 IP
  2. rainborick

    rainborick Well-Known Member

    Messages:
    424
    Likes Received:
    33
    Best Answers:
    0
    Trophy Points:
    120
    #2
    preg_replace() won't work well for this because regular expressions do pattern matching and your data doesn't have a pattern; it has a structure, which is a very different beast. You need to parse the document to extract the data you want. You could start with the PHP DOM documentation. Good luck!
     
    rainborick, Apr 5, 2012 IP
  3. ROOFIS

    ROOFIS Well-Known Member

    Messages:
    1,234
    Likes Received:
    30
    Best Answers:
    5
    Trophy Points:
    120
    #3
    Try strip_tags and leave the ones you need. Personally I'd pull the content into an array and phrase from there,
    but DOM is considered the best way to go by general consensus.


    :D




    ROOFIS
     
    ROOFIS, Apr 6, 2012 IP
  4. dropdrop

    dropdrop Active Member

    Messages:
    142
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    53
    #4
    Try this, i am not try before, but it should be a simple PHP script:

    But, since you had DIV inside the DIV, it may be need recursive to run the preg_replace().

    //Output should be : Another CONTENT
     
    dropdrop, Apr 6, 2012 IP
  5. ROOFIS

    ROOFIS Well-Known Member

    Messages:
    1,234
    Likes Received:
    30
    Best Answers:
    5
    Trophy Points:
    120
    #5
    @thankyou


    Try this 100% working example:

    
    <?php
    $mytext = '<div class="group" style="margin-left:10px; margin-bottom:10px;"><div class="group" style="margin-left:10px; margin-bottom:10px;">Another CONTENT</div></div>';
    echo strip_tags($mytext);
    
    //Output : Another CONTENT
    ?>
    
    PHP:
    For the example you've given strip-tags is by far the easiest course of action to take without the overhead from complex regex syntax. :eek:






    ROOFIS
     
    Last edited: Apr 6, 2012
    ROOFIS, Apr 6, 2012 IP