簡體   English   中英

在PHP中使用preg_replace的正則表達式

[英]Regex with preg_replace in PHP

很久以前,我還沒有玩過PHP和regex,我想找到一個可以完成以下工作的regex。

我的字符串包含:

<pre code="...">some piece of code</pre> other non code content <pre code="...">some piece of code</pre> other non code content...

目標是將所有<pre>code</pre> by替換<pre>code</pre> by

code
...`

<pre>&</pre>中的"code"也應使用htmlspecialchars...進行轉義htmlspecialchars...

我已經嘗試過一些正則表達式,但沒有成功。

任何想法?

謝謝

通常,使用RegEx解析HTML是一個壞主意。 有很多簡單的方案,其中RegEx足以解決特定問題,這很棒。

我認為在您的情況下使用RegEx是一個壞主意,它不能涵蓋所有情況,並且可能不安全。 您可能正在嘗試防止XSS漏洞,並且基於RegEx的解決方案始終容易出錯。

但是出於完整性考慮:

preg_replace_callback(
    '/(<\\s*pre(?:\\s[^>]+)?>)(.*?)(<\\/\s*pre\s*>)/',
    function ($match) {
        return $match[1].htmlspecialchars($match[2]).$match[3];
    },
    $html
);

暫無
暫無

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

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