我在创建用于SyntaxHighlighter的BBCode时遇到一些问题
function bb_parse_code($str) {
while (preg_match_all('`\[(code)=?(.*?)\]([\s\S]*)\[/code\]`', $str, $matches)) foreach ($matches[0] as $key => $match) {
list($tag, $param, $innertext) = array($matches[1][$key], $matches[2][$key], $matches[3][$key]);
switch ($tag) {
case 'code': $replacement = '<pre class="brush: '.$param.'">'.str_replace(" ", " ", str_replace(array("<br>", "<br />"), "\n", $innertext))."</pre>"; break;
}
$str = str_replace($match, $replacement, $str);
}
return $str;
}我有bbcode:
[b]bold[/b]
[u]underlined[/u]
[code=js]function (lol) {
alert(lol);
}[/code]
[b]bold2[/b]
[code=php]
<? echo 'lol' ?>
[/code]这将返回以下内容:

我知道问题出在允许任何字符的正则表达式的([\s\S]*)上,但是如何让代码在换行的情况下工作呢?
发布于 2012-10-24 03:04:59
您应该使用以下模式:
`\[(code)=?(.*?)\](.*?)\[/code\]`s有几个变化:
末尾的switch to
s修饰符,这会导致. to match new lines too.
https://stackoverflow.com/questions/13037243
复制相似问题