-2

I'm writing a chat program and what I want to do is replace all the html tags with > < tags but allow specific tags to still work (img, a etc.)

This is what I have so far but it does not appear to be working:

$value = '
<img src="/blah/blah.gif" />
<img src="/blah/blah.gif">
<b>blah</b>
<strong>test</strong>
<script>test</script>
<script>test
<script
type="text">

<script></script>
<script
>

</script>

<script>blah

<br />

';
$tags = 'b|img'; // allow these tags

echo preg_replace("~<((/(?!$tags)|(?!/)(?!$tags)).*?)>~is", '&lt;$1&gt;', $value);

The result of the output is this:

<img src="/blah/blah.gif" />
<img src="/blah/blah.gif">
<b>blah</b>
&lt;strong&gt;test&lt;/strong&gt;
&lt;script&gt;test&lt;/script&gt;
&lt;script&gt;test
&lt;script
type="text"&gt;

&lt;script&gt;&lt;/script&gt;
&lt;script
&gt;

&lt;/script&gt;

&lt;script&gt;blah

<br />

As you can see it doesn't appear to be stripping the
tag out as well even though this is not in the $tags variable as an allowed tag.

4

2 回答 2

0
$value = '
<img src="/blah/blah.gif" />
<img src="/blah/blah.gif">
<b>blah</b>
<strong>test</strong>
<script>test</script>
<script>test
<script
type="text">

<script></script>
<script
>

</script>

<script>blah

<br />

';

echo strip_tags($value,'<b><img>');

回声:

<img src="/blah/blah.gif" />
<img src="/blah/blah.gif">
<b>blah</b>
test
test
test







blah
于 2013-02-14T09:56:15.960 回答
0

我实际上建议无条件地将所有 HTML 标记替换为&lt;/ &gt;,然后引入 BBCode 支持:它会让您免于令人难以置信的头痛。

至于最初的问题,我所知道的可靠地做到这一点的唯一方法是解析输入 HTML,丢弃所有冗余空格,然后进行模式匹配。

于 2013-02-14T09:57:04.280 回答