2011-04-02 79 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