2017-02-24 39 views
0

我要替換所有<pre><code>CONTENT</code></pre>內容。php preg_replace所有發生的特定html標記

<pre class="language-php"><code>m1 
</code></pre> 
lets go 
<pre class="language-php"><code>m2 
</code></pre> 

但運行preg_replace("/<pre(.*)<\/pre>/s", "SAMAN", $input_lines);會輸出這樣的:

SAMAN 

,而我需要這樣的輸出:

SAMAN lets go SAMAN 

here是我的實際測試結果

回答

2

*量詞是貪婪的,追加它與?把它變成非貪婪。即你的正則表達式應該是:/<pre(.*?)<\/pre>/s

0

的代碼是:

<?php 
$input_lines='<pre class="language-php"><code>m1 
</code></pre> 
lets go 
<pre class="language-php"><code>m2 
</code></pre>'; 

$new_string=preg_replace("/(\r?\n?<pre.*?\/pre>\r?\n?)/s","SAMAN",$input_lines); 
echo $new_string; 
?> 

輸出:

SAMAN lets go SAMAN 

正則表達式模式說明:

(     # Begin capture group 
    \r?\n?   # Optional newline characters on Windows and Linux 
    <pre.*?\/pre> # Match from opening pre tag to closing pre tag 
    \r?\n?   # Optional newline characters on Windows and Linux 
)     # End capture group 
/s     # Force all dots in pattern to allow newline characters 

我的回答非常近似於LeleDumbo的答案,可能會對提問者滿意。我只是從結束標記中省略了不必要的<,並且包含了一些換行符,這樣$ new_string中沒有任何隱藏字符(這可能是也可能不是問題,具體取決於使用情況)。