2012-01-30 68 views
1

我想什麼(這是一個靜態的CPP只)=>需要一個通用的PHP正則表達式做了preg_replace

$str1 = "<pre    class="brush:cpp">"; 

$temp = preg_replace('/&lt;pre\s+class=&quot;brush:cpp&quot;&gt;/','<pre class="brush:cpp">',$str1); 

echo $temp . "\n"; 

輸出=>

<pre class="brush:cpp"> 

但是$ STR1可以

"&lt;pre class=&quot;brush:cpp&quot;&gt;" 
"&lt;pre class=&quot;brush:java&quot;&gt;" 
"&lt;pre class=&quot;brush:php&quot;&gt;" 
"&lt;pre class=&quot;brush:python&quot;&gt;" 

對於那些輸出應爲=>

<pre class="brush:cpp"> 
<pre class="brush:java"> 
<pre class="brush:php"> 
<pre class="brush:python"> 

注意:我不能使用html_entity_decode,因爲文本將包含其他正常字符串,並且&lt;br&gt;對於<br/>,我不想爲所有文本執行html_entity_decode。

我需要一個通用的正則表達式來捕捉cpp/java/php/python。我如何編寫一個通用的正則表達式來保存模式的一部分,並保持它在替換字符串中。

回答

2

我相信這樣的事情會工作:

preg_replace('/&lt;pre\s+class=&quot;brush:(cpp|java|php|python)&quot;&gt;/','<pre class="brush:$1">',$str1); 

它使用一個捕獲組捕獲其結局是存在,它可以是CPP/JAVA/PHP/Python中的一個。替換是使用反向引用#1進行的,反向引用#1會將捕獲的結尾放置到最後。

這是an example

+0

有什麼辦法避免輸入'CPP |的Java | PHP | python'明確?任何方式來爲這些寫一些通用表達式?這些將是帶[a-z]字母的語言/單詞。 – shibly 2012-01-30 04:00:35

+0

是的,做'([a-zA-Z] +)'而不是'(cpp | java | php | python)' – nickb 2012-01-30 04:09:15

1

使用

preg_replace('/&lt;pre\s+class=&quot;brush:(.*?)&quot;&gt;/', 
      '<pre class="brush:$1">', 
      $str1);