PHP - 对标签内的所有内容进行编码 <code>
PHP - encode everything inside tag <code>
我只是想让我的博客尽可能易于编码。
我的问题是:
如何(如果可能的话)通过 htmlentities();
对 HTML 标签 <code>
内的所有内容进行编码
我想要这个:
如果我post关于制作某物,我将不需要通过一些在线编码器对其进行编码,而只需制作类似
的东西
"Just simply put
<code>
encoded code
</code>
and this <b>bold</b> text will be bold, because it isn't inside <code>
是否可以在 php 代码中使用某些功能,例如
encode_tags($text,"<code>","</code>");
?
您的输入字符串(稍作编辑以澄清我的回答):
$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
,用于忽略组 (*)
上的换行符。
上面的代码是懒惰的(见底部的links)并且也会不匹配不完整的标签(例如<code>
没有对应的</code>
)。
第 2 步:
根据需要对每个找到的子字符串进行 HTML 更改(您应该熟悉如何 preg_match_all
returns 来自函数的数据,请参阅底部的 link ):
$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);
输出:
以上将输出:
Just simply put
<p>encoded code</p>
and this bold text will be bold, because it isn't inside <b>code tags</b>
你应该对preg_match_* family of PHP functions as well as general PCRE REGEX有一个熟悉的认识。
另请阅读this here, and here and read this and especially this。
干杯
我只是想让我的博客尽可能易于编码。 我的问题是:
如何(如果可能的话)通过 htmlentities();
<code>
内的所有内容进行编码
我想要这个: 如果我post关于制作某物,我将不需要通过一些在线编码器对其进行编码,而只需制作类似
的东西"Just simply put
<code>
encoded code
</code>
and this <b>bold</b> text will be bold, because it isn't inside <code>
是否可以在 php 代码中使用某些功能,例如
encode_tags($text,"<code>","</code>");
?
您的输入字符串(稍作编辑以澄清我的回答):
$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
,用于忽略组 (*)
上的换行符。
上面的代码是懒惰的(见底部的links)并且也会不匹配不完整的标签(例如<code>
没有对应的</code>
)。
第 2 步:
根据需要对每个找到的子字符串进行 HTML 更改(您应该熟悉如何 preg_match_all
returns 来自函数的数据,请参阅底部的 link ):
$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);
输出:
以上将输出:
Just simply put
<p>encoded code</p>
and this bold text will be bold, because it isn't inside <b>code tags</b>
你应该对preg_match_* family of PHP functions as well as general PCRE REGEX有一个熟悉的认识。
另请阅读this here, and here and read this and especially this。
干杯