PHP - 在标记内显示标记为文本

时间:2012-03-11 10:33:33

标签: php html

很抱歉无法使标题更清晰。

基本上我可以在我的页面上键入文本,其中所有HTML-TAGS都被删除,除了我允许的几个。

我想要的是能够输入我想要的所有标签,以纯文本形式显示,但前提是它们在'code'标签内。我知道我可能会使用htmlentities,但我怎么能只影响'code'标签内的标签呢?

可以吗?

先谢谢你们。

例如,我有$ _POST ['content'],这是网页上显示的内容。并且是我遇到问题的所有输出的变量。

假设我发布了一段文字,除了少数几个标签外,所有标签都会被删除,包括“代码”标签。

在代码标记中我放置了代码,例如HTML信息,但是这应该显示为文本。如何将HTML标记转义为仅在“代码”标记中以纯文本形式显示?

以下是我可以输入的示例:

Hi there, this is some text and this is a picture <img ... />. 
Below I will show you the code how to do this image:

<code>
    <img src="" />
</code>

标签内的所有内容都应显示为纯文本,这样它们就不会从PHP的strip_tags中删除,而只会从标签中的html标签中删除。

3 个答案:

答案 0 :(得分:0)

如果它是严格的代码标签,那么它可以很容易地完成。

首先,通过“' or '”的任何出现来爆炸你的字符串。 例如,字符串:

Hello <code> World </code>

应成为4项数组:{Hello,,World!,}

现在循环遍历从0开始的数组并递增4.您点击的每个元素,运行当前脚本(删除除允许的标记之外的所有标记)。 现在循环遍历从2开始的数组并以4递增。您点击的每个元素,只需在其上运行htmlspecialentities。

内爆您的数组,现在您有一个字符串,其中标记内的任何内容都已完全清理,标记之外的任何内容都会被部分清理。

答案 1 :(得分:0)

以下是一些示例代码:

$parsethis = '';
$parsethis .= "Hi there, this is some text and this is a picture <img src='http://www.google.no/images/srpr/logo3w.png' />\n";
$parsethis .= "Below I will show you the code how to do this image:\n";
$parsethis .= "\n";
$parsethis .= "<code>\n";
$parsethis .= "    <img src='http://www.google.no/images/srpr/logo3w.png' />\n";
$parsethis .= "</code>\n";

$pattern = '#(<code[^>]*>(.*?)</code>)#si';

$finalstring = preg_replace_callback($pattern, "handle_code_tag", $parsethis);

echo $finalstring;

function handle_code_tag($matches) {
    $ret = '<pre>';
    $ret .= str_replace(array('<', '>'), array('&lt;', '&gt;'), $matches[2]);
    $ret .= '</pre>';
    return $ret;
}

它的作用:

首先使用preg_replace_callback我匹配<code></code中的所有代码,将其发送到我的回调函数handle_code_tag,该函数会转义内容中的所有小于和大于标签。匹配数组将在1中包含完整匹配的字符串,而(.*?) in [2].#si` s 的匹配意味着匹配。跨线刹和 i 表示不区分大麻

渲染的输出在我的浏览器中如下所示: enter image description here

答案 2 :(得分:0)

这是我发现的解决方案,它对我来说非常有效。 谢谢大家的帮助!

function code_entities($matches) {
    return str_replace($matches[1],htmlentities($matches[1]),$matches[0]);
}

$content = preg_replace_callback('/<code.*?>(.*?)<\/code>/imsu',code_entities, $_POST['content']);
相关问题