我正在使用WordPress
,并希望创建一个只将htmlspecialchars
函数应用于<code></code>
标记之间包含的代码的函数。我理解这可能相当简单,但我对PHP并不熟悉,也找不到任何关于如何做到这一点的参考资料。
到目前为止,我有以下几点:
function FilterCodeOnSave( $content, $post_id ) {
return htmlspecialchars($content, ENT_NOQUOTES);
}
显然,上面的内容非常简单,并在我页面的整个内容上执行htmlspecialchars。我需要限制该函数仅适用于代码标记之间的HTML (每个页面上可能有多个代码标记)。
任何帮助都将不胜感激。
谢谢,詹姆斯
发布于 2014-04-10 09:19:41
编辑:更新以避免多个代码标记
试试这个:
<?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;
?>
发布于 2014-04-10 09:21:06
使用DOMDocument获取所有标签;
// in this example $dom is an instance of DOMDocument
$code_tags = $dom->getElementsByTagName('code');
if ($code_tags) {
foreach ($code_tags as $node) {
// [...]
}
// [...]
}
https://stackoverflow.com/questions/22983258
复制相似问题