我正在使用WordPress
,并希望创建一个函数,该函数仅将PHP函数htmlspecialchars
应用于包含在<code></code>
标记之间的代码。我很感激这可能相当简单,但我是PHP的新手,找不到任何关于如何做到这一点的参考资料。
到目前为止,我有以下内容:
function FilterCodeOnSave( $content, $post_id ) {
return htmlspecialchars($content, ENT_NOQUOTES);
}
显然,上面的内容非常简单,并对我页面的整个内容执行htmlspecialchar。我需要限制该函数仅适用于代码标记之间的HTML(每个页面上可能有多个代码标记)。
如有任何帮助,我们将不胜感激。
谢谢,James
EDIT:更新以避免多个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获取所有<代码>标签;
// in this example $dom is an instance of DOMDocument
$code_tags = $dom->getElementsByTagName('code');
if ($code_tags) {
foreach ($code_tags as $node) {
// [...]
}
// [...]
}
我知道这有点晚了,但您可以先调用htmlspecialchars函数,然后在输出时调用htmlspecicalchars_decode函数