简体   繁体   English

php上的htmlentities <code></code> 只要!

[英]php htmlentities on <code></code> only!

I want to run htmlentities() only on the contents within <code> things to strip </code> 我只想对<code>要剥离</ code>的内容中的内容运行htmlentities()

I Wrote a function that takes a string and finds the content in between <code> </code> 我编写了一个函数,该函数需要一个字符串并在<code> </ code>之间找到内容

function parse_code($string) {

  // test the string and find contents with <code></code> preg_match('@<code>(.*?)</code>@s', $string, $matches); // return the match if it succeeded if($matches) { return $matches[1]; }else { return false; } } 

However I need some help with a function that will will actually run htmlentities(); 但是,我需要有关将实际运行htmlentities()的函数的帮助。 on the contents within <code> </code> and then implode() it all back together. 放在<code> </ code>中的内容上,然后将implode()全部放回原处。 For example lets say we have the string below. 例如,假设我们有下面的字符串。

<div class="myclass" rel="stuff"> things in here </div>
<code> only run htmlentites() here so strip out things like < > " ' & </code>
<div> things in here </div>

Once again, The function would need to keep all contents of the string the same but only modify and run htmlentities() on the contents of <code> </code> 再次,该函数将需要使字符串的所有内容保持相同,但只对<code> </ code>的内容进行修改并运行htmlentities()

You can simplify this with using a custom callback function: 您可以使用自定义回调函数简化此操作:

$html = preg_replace_callback(
     "@  (?<= <code>)  .*?  (?= </code>)  @six",
     "htmlentities_cb", $html
);

function htmlentities_cb($matches) {
    return htmlentities($matches[0], ENT_QUOTES, "UTF-8");
}

The syntax for matching the enclosing code tags is called lookbehind and lookahead assertion . 匹配封闭代码标签的语法称为lookbehind和lookahead断言 It simplifies the callback and avoids implode() later, because the assertion matches itself do not become part of $matches[0]. 它简化了回调并避免了以后的implode(),因为断言匹配本身不会成为$ matches [0]的一部分。 While @six is for case-insensitve tag matches and allows whitespace in the regex to make it more readable. @six用于不区分大小写的标记匹配,并允许正则表达式中的空格使其更具可读性。

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

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