[英]How to use htmlspecialchars only on <code></code> tags.
我正在使用WordPress
并想创建一个函数,该函数将 PHP 函数htmlspecialchars
仅应用于<code></code>
标记之间包含的代码。 我很欣赏这可能相当简单,但我是 PHP 新手,找不到任何关于如何执行此操作的参考。
到目前为止,我有以下几点:
function FilterCodeOnSave( $content, $post_id ) {
return htmlspecialchars($content, ENT_NOQUOTES);
}
显然,上面的内容非常简单,并对我的页面的整个内容执行 htmlspecialchars。 我需要将该功能限制为仅适用于代码标签之间的 HTML(每个页面上可能有多个代码标签)。
任何帮助,将不胜感激。
谢谢,詹姆斯
编辑:更新以避免多个 CODE 标签
尝试这个:
<?php
// test data
$textToScan = "Hi <code>test12</code><br>
Line 2 <code><br>
Test <b>Bold</b><br></code><br>
Test
";
// debug:
echo $textToScan . "<hr>";
// the regex pattern (case insensitive & multiline
$search = "~<code>(.*?)</code>~is";
// first look for all CODE tags and their content
preg_match_all($search, $textToScan, $matches);
//print_r($matches);
// now replace all the CODE tags and their content with a htmlspecialchars() content
foreach($matches[1] as $match){
$replace = htmlspecialchars($match);
// now replace the previously found CODE block
$textToScan = str_replace($match, $replace, $textToScan);
}
// output result
echo $textToScan;
?>
使用DOMDocument获取所有 <code> 标签;
// in this example $dom is an instance of DOMDocument
$code_tags = $dom->getElementsByTagName('code');
if ($code_tags) {
foreach ($code_tags as $node) {
// [...]
}
// [...]
}
我知道这有点晚了,但是您可以先调用htmlspecialchars函数,然后在输出时调用htmlspecialchars_decode函数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.