簡體   English   中英

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

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

我只想對<code>要剝離</ code>的內容中的內容運行htmlentities()

我編寫了一個函數,該函數需要一個字符串並在<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; } } 

但是,我需要有關將實際運行htmlentities()的函數的幫助。 放在<code> </ code>中的內容上,然后將implode()全部放回原處。 例如,假設我們有下面的字符串。

<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>

再次,該函數將需要使字符串的所有內容保持相同,但只對<code> </ code>的內容進行修改並運行htmlentities()

您可以使用自定義回調函數簡化此操作:

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

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

匹配封閉代碼標簽的語法稱為lookbehind和lookahead斷言 它簡化了回調並避免了以后的implode(),因為斷言匹配本身不會成為$ matches [0]的一部分。 @six用於不區分大小寫的標記匹配,並允許正則表達式中的空格使其更具可讀性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM