2011-04-02 74 views
0

我有串這樣的:PHP - 轉換代碼段從字符串到HTML字符

<a href="http://google.com"> link </a> 
[code lang="html" anotherargument="foo"...] 
<a href="http://google.com"> link </a> 
[/code] 

我如何轉換[code...][/code]之間包裹HTML字符的代碼?

這樣的:

<a href="http://google.com"> link </a> 
[code lang="html" anotherargument="foo"...] 
&lt;a href=&quot;http://google.com&quot;&gt; link &lt;/a&gt; 
[/code] 

回答

1

試試這個

preg_match_all('`\[code[^\]]*+]([^\[]*+)\[/code\]`i', $html, $matches, PREG_SET_ORDER); 

foreach ($matches as $match) { 
    $html = str_replace($match[1], htmlentities($match[1]), $html); 
} 
+0

謝謝。你知道我該怎麼做'

 ...
'嗎? – Alex 2011-04-02 10:43:05

+0

將模式字符串更改爲'| ]*+>([^<]*+) |我' – chriso 2011-04-02 11:29:29

+0

不工作:( – Alex 2011-04-02 22:56:07

1

您可以使用帶回調的正則表達式 - 因此匹配代碼標記之間的內容,然後通過運行函數來替換。

事情是這樣的未經測試的代碼:

$str = preg_replace_callback('/(\[code.+?\])(.+?)(\[\/code\])/', create_function(
      '$m', 
      'return $m[1] . htmlentities($m[2]) . $m[3];' 
     ),$str) 
+0

我想你的意思['preg_replace_callback'](http://www.php.net/manual/en/function .preg-replace-callback.php) – chriso 2011-04-02 08:30:27

+0

你是對的 - 我已更正 – 2011-04-02 11:02:22