php 如何只删除字符串中的html标签?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11412758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:27:53  来源:igfitidea点击:

How to remove only html tags in a string?

phpregex

提问by pushpa

I have written code for removing HTML tags, but it is also removing a<btype of strings. I want it to not to remove strings like 2<3or a<b.

我已经编写了用于删除 HTML 标签的代码,但它也在删除a<b字符串类型。我希望它不要删除像2<3或这样的字符串a<b

$term="a<b";
echo "Text is--->".preg_replace('/(?:<|&lt;).+?(?:>|&gt;)/', '', $term);

How do I remove html tags in a string, without removing LT or GT?

如何删除字符串中的 html 标签,而不删除 LT 或 GT?

回答by ChangHun Lee

Sorry I had not validate enough.

对不起,我没有足够的验证。

I have checked php5-cli expression below.

我已经检查了下面的 php5-cli 表达式。

(?:<|&lt;)\/?([a-zA-Z]+) *[^<\/]*?(?:>|&gt;)

PHP code goes:

PHP代码去:

#!/usr/bin/php 
<?php

$str = "<html></html>
a<b 1<2 3>1 
<body>1>2</body>
<style file=\"'googe'\" alt=\"google\">hello world</style>
<have a good efghijknopqweryuip[]asdfgghjkzxcv bnm,.me>hello world<> google com</s>
<a se=\"font: googe;\">abcde</a>";

echo "text--->".preg_replace('/(?:<|&lt;)\/?([a-zA-Z]+) *[^<\/]*?(?:>|&gt;)/', '', $str)."\n";

?>

Result:

结果:

text--->
a<b 1<2 3>1 
1>2
hello world
hello world<> google com
abcde

回答by ChangHun Lee

Use strip tags function of php

使用php的strip tags功能

echo strip_tags($html)

回答by Ali Hesari

Remove all HTML tags from PHP string with content!

从带有内容的 PHP 字符串中删除所有 HTML 标签!

Let say you have string contains anchor tag and you want to remove this tag with content then this method will helpful.

假设您有包含锚标记的字符串,并且您想删除带有内容的此标记,那么此方法将有所帮助。

$srting = '<a title="" href="/index.html"><b>Some Text</b></a> a<b';

echo strip_tags_content($srting);

function strip_tags_content($text) {

    return preg_replace('@<(\w+)\b.*?>.*?</>@si', '', $text);

 }

Output:

输出:

a < b

a < b

Retrieved from: Remove all html tags from php string

取自:从 php 字符串中删除所有 html 标签

回答by ChangHun Lee

Strip_tags function is good solution.

Strip_tags 函数是很好的解决方案。

But if you need regex, use expression below.

但是如果您需要正则表达式,请使用下面的表达式。

(?:<|&lt;)\/?([a-z]+) *[^\/(?:<|&lt;)]*?(?:>|&gt;)

(?:<|&lt;)\/?([a-z]+) *[^\/(?:<|&lt;)]*?(?:>|&gt;)

回答by Burimi

Use strip_tags

使用strip_tags

//If you want to allow some tags
$term = strip_tags($term,"<b>");