如何在不使用strip_tags?</div>的情况下从变量中删除<div>标记

时间:2012-09-19 12:51:29

标签: php regex html5

这是我的代码

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

我想在不使用strip_tags的情况下删除其html标记<div>。 我需要$str="this is the variable" 因为我的服务器不能使用strip_tags。 我知道preg_replace是可行的。但我不知道正则表达式。 所以请建议我的解决方案。

提前谢谢。

6 个答案:

答案 0 :(得分:6)

如果DIV标记包含属性,则此变体也起作用:

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

答案 1 :(得分:4)

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

当然,不要用正则表达式解析HTML: - )

<强> DEMO

答案 2 :(得分:4)

如果您要删除文本周围的标记并保持其他标记使用:

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

警告:这将仅删除第一个包装标记

并将HTML解析为标记。

答案 3 :(得分:0)

你可以这样做:

$str="<div>this is the variable</div>";
$str = preg_replace('/<(.*?)>/i', '', $str);

将删除所有html标记,而不仅仅是<div>

答案 4 :(得分:0)

使用

preg_replace("#<div>(.*?)</div>#s", "$1", $s);

s - DOTALL 修饰符,使 . 匹配换行符。

# - 与 / 不同的正则表达式分隔符,多亏了它们,无需转义 /

说明

--------------------------------------------------------------------------------
  <div>                    '<div>'
--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    .*?                      any character (0 or more times, the least amount possible))
--------------------------------------------------------------------------------
  )                        end of \1
--------------------------------------------------------------------------------
  </div>                   '</div>'

$1 是对用括号内的第一组捕获的文本的反向引用

答案 5 :(得分:-1)

如果您只是在这样的div标签之后,可以尝试

preg_replace("</?div>","",$string);

当然有人可能会提到not to parse html with regex

相关问题