简体   繁体   English

PHP-对标签内的所有内容进行编码

[英]PHP - encode everything inside tag <code>

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(); 如何(如果可能)通过htmlentities();对HTML标记<code>的所有内容进行编码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 是否有可能在PHP代码内部使用某些功能,就像

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

?

Your input string ( minorly edited to clarify my answer): 您的输入字符串(经过轻微编辑以阐明我的答案):

$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>";

Step 1: 第1步:
Break your string into parts as surrounded by by <code> . 将您的字符串分成由<code>包围的部分。 Note your regex should use # not / as the delimiters so you don't need to care about the / in your </code> . 注意:您正则表达式应该使用#/作为分隔符,所以你并不需要关心的/在你的</code>

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

Note the s at the end of the REGEX for ignoring line breaks on the group (*) . 注意REGEX末尾的s可以忽略组(*)上的换行符。

The above code is lazy (see links at the bottom) and will also not match incomplete tags (such as <code> with no corresponding </code> ). 上面的代码是惰性的(请参阅底部的链接),也不会匹配不完整的标记(例如<code>没有相应的</code> )。

Step 2: 第2步:
Make the HTML changes as required to each of the found substrings (You should be familiar with how preg_match_all returns the data from the function, see link at the bottom): 根据需要对每个找到的子字符串进行HTML更改(您应该熟悉preg_match_all如何从函数返回数据的方式,请参见底部的链接):

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

Step 3: 第三步:
Apply the changes to the original values (theses are NOT the same as the converted values, used in Step 2): 更改应用到原始值(论文是一样的转换后的值,在步骤2中使用):

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

Output: 输出:

The above will then output: 以上内容将输出:

Just simply put 简而言之

<p>encoded code</p> <p>编码代码</ p>

and this bold text will be bold, because it isn't inside <b>code tags</b> 并且此粗体文本将为粗体,因为它不在<b>代码标签</ b>中


You should have a familiar understanding of preg_match_* family of PHP functions as well as general PCRE REGEX . 您应该对preg_match_ *系列PHP函数以及一般的PCRE REGEX有一个熟悉的了解。

Please also read this here , and here and read this and especially this . 也请阅读此这里 ,并在这里阅读 ,尤其是这个

Cheers 干杯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM