How can i remove <div> tag from variable without using strip_tags?

16,671

Solution 1

$s = "<div>this is the variable</div>";
echo preg_replace("/<div>(.*?)<\/div>/", "$1", $s);
// this is the variable

And of course, don't parse HTML with regex :-)

DEMO.

Solution 2

This variant works also if the DIV tag contains attributes:

$str = '<div id="some_id">this is the variable</div>';
$str = preg_replace('/\<[\/]{0,1}div[^\>]*\>/i', '', $str);
echo $str;

Solution 3

If you want to remove the tag around your text and keep the other tags use:

$node = new DOMDocument();
$str = $node->loadXML($str)->firstChild->textContent;

WARNING: this will remove the first wrapper tag only

and this parses HTML as a markup, which it is.

Share:
16,671
Krishna Karki
Author by

Krishna Karki

Web Developer

Updated on June 28, 2022

Comments

  • Krishna Karki
    Krishna Karki almost 2 years

    Here is my code

    $str="<div>this is the variable</div>";
    

    I want to remove its html tag <div> without using strip_tags. I need $str="this is the variable" Because my server is not working with strip_tags. I know it is possible with preg_replace. but i dont know regex. So please suggest me the solution.

    Thank you in advance.

  • Krishna Karki
    Krishna Karki over 11 years
    Thnx Joa Silva for answer. but its amazing to me that your code is working good on my local but not on my server. And i also dont understand "And of course, don't parse HTML with regex"
  • João Silva
    João Silva over 11 years
    @KrishnaKarki: It's generally not advisable to use regex to parse HTML; it's usually better to use an HTML Parser. However, if you just want to extract the text between that div, and it has a static structure, it's fine to use a regex. Having said that, it's strange that works locally and not on your server. Are you sure the string is the same?
  • Krishna Karki
    Krishna Karki over 11 years
    yes string is the same. I just copied your code and pasted to my project for testing first.
  • João Silva
    João Silva over 11 years
    @KrishnaKarki: What are you doing with the result in your production code? echoing it? Saving it in a variable, i.e., $result = preg_replace(...)? Are the PHP versions the same?
  • Krishna Karki
    Krishna Karki over 11 years
    I m echoing the variable. and my PHP Version is 5.2.17
  • Krishna Karki
    Krishna Karki over 11 years
    error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE); this is my error reporting setting. but there is no error
  • Razvan.432
    Razvan.432 over 5 years
    $str = preg_replace('/^\<[\/]{0,1}div[^\>]*\>/i', '', $str); use ^ so that it will remove only the first div