2012-10-29 18 views
0

我有這樣的preg_replace模式和替換:我想html_entity_decode這些標籤之間的內容html_entity_decode在特定的正則表達式爲的preg_replace

$patterns = array(
    "/<br\W*?\/>/", 
    "/<strong>/", 
    "/<*\/strong>/", 
    "/<h1>/", 
    "/<*\/h1>/", 
    "/<h2>/", 
    "/<*\/h2>/", 
    "/<em>/", 
    "/<*\/em>/", 
    '/(?:\<code*\>([^\<]*)\<\/code\>)/', 
); 
$replacements = array(
    "\n", 
    "[b]", 
    "[/b]", 
    "[h1]", 
    "[/h1]", 
    "[h2]", 
    "[/h2]", 
    "[i]", 
    "[/i]", 
    '[code]***HTML DECODE HERE***[/code]', 
); 

在我的字符串: <code> &lt; $gt; </code>但讓我的陣列結構的預浸料代替

所以這個:<code> &lt; &gt; </code>將是這樣的:[code] < > [/code]

任何幫助將非常感激,謝謝!

回答

1

您不能在替換字符串中對其進行編碼。作爲PoloRM建議,你可以使用preg_replace_callback專門爲您上次更換,而不是:

function decode_html($matches) 
{ 
    return '[code]'.html_entity_decode($matches[1]).'[/code]'; 
} 

$str = '<code> &lt; &gt; </code>'; 
$str = preg_replace_callback('/(?:\<code*\>([^\<]*)\<\/code\>)/', 'decode_html', $str); 

同樣地,使用create_function

$str = preg_replace_callback(
    '/(?:\<code*\>([^\<]*)\<\/code\>)/', 
    create_function(
     '$matches', 
     'return \'[code]\'.html_entity_decode($matches[1]).\'[/code]\';' 
    ), 
    $str 
); 

或者,如PHP 5.3.0的:

$str = preg_replace_callback(
    '/(?:\<code*\>([^\<]*)\<\/code\>)/', 
    function ($matches) { 
     return '[code]'.html_entity_decode($matches[1]).'[/code]'; 
    }, 
    $str 
); 

但請注意,在所有三種情況下,您的模式並非真正最佳。首先,你不需要逃避那些<>(但這只是爲了可讀性)。其次,你的第一個*允許無限重複(或省略)字母e。我想你想允許屬性。第三,您不能在<code>中包含其他標籤(因爲[^<]不會與它們匹配)。在這種情況下,也許你應該ungreedy重複去,而不是(我也改變了方便的分隔符):

~(?:<code[^>]*>(.*?)</code>)~ 

正如你已經可以看到,這還遠遠不夠完善(處於正確匹配HTML條款第一名)。因此,強制性提醒:don't use regex to parse HTML。使用DOM解析器你會好很多。 PHP帶來built-in one,還有this very convenient-to-use 3rd-party one

+0

謝謝你的回答,我想我會考慮的DOM解析器,但它是一個比較複雜一點:對 – user990463

+0

@ user990463,尤其是第二個我聯繫實在是沒有那麼複雜。它非常易於使用(只需閱讀他們的文檔並查看一些示例)。 –

+0

是的我想使用這一個,但技術問題(不取決於我)我不能安裝第三方擴展:( – user990463