PHP - 对标记<code>

时间:2018-05-14 17:29:18

标签: php html encode

I just want to make my blog as easy to code as it can be. And my question is:

How(if it's possible) to encode everything inside HTML tag <code> by htmlentities();

I'm want this: If I make a post about making something, I will don't need to encode it by some encoder online but simply make something like

"Just simply put
<code>
encoded code
</code>
and this <b>bold</b> text will be bold, because it isn't inside <code>

is it possible inside php code with some function used to be like

encode_tags($text,"<code>","</code>");

?

1 个答案:

答案 0 :(得分:0)

您的输入字符串(经过轻微编辑以澄清我的答案):

$string = "Just simply put
<code>
<p>encoded code</p>
</code>
and this <b>bold</b> text will be bold, 
because it isn't inside <code><b>code tags</b></code>";

第1步:
将字符串分成由<code>包围的部分。请注意,您的正则表达式应使用#而不是/作为分隔符,因此您无需关心/中的</code>

 preg_match_all("#<code>(.*?)</code>#is", $string, $codes);

请注意REGEX末尾的s忽略组(*)上的换行符。

以上代码是懒惰的(请参阅底部的链接),并且匹配不完整的标记(例如<code>没有对应的</code>)。

第2步:
根据需要对每个找到的子字符串进行HTML更改(您应该熟悉preg_match_all如何从函数返回数据,请参阅底部的链接):

$replace = [];
foreach($codes[1] as $key=>$codeBlock ){
    $replace[$key] = htmlentities($codeBlock, ENT_QUOTES, "UTF-8", false);
}
unset($key, $codeBlock);

第3步:
将更改应用于原始值(这些 NOT 与转换后的值相同,在步骤2中使用):

foreach($codes[0] as $key=>$replacer){
    $string = str_replace($replacer, $replace[$key], $string);
}
unset($key, $replacer, $replace);

输出:

然后输出以上内容:

  

只需简单地放

     

&lt; p&gt;编码代码&lt; / p&gt;

     

粗体文字将为粗体,因为它不在&lt; b&gt;代码标记内&lt; / b&gt;

您应该熟悉preg_match_* PHP函数族以及一般PCRE REGEX

另请阅读this herehereread this,尤其是this

干杯