2

我正在尝试模拟一个 bbcode 标签,如下面的代码:

[code]this is code to render[/code]
[code attributeA=arg]this is code to render[/code]
[code attribute C=arg anotherAtributte=anotherArg]this is code to render[/code]

如您所见,代码标签可以根据需要获取任意数量的属性,也可以在同一个“发布”中存在过多的代码标签。我只处理过最简单的标签,如 img、b、a、i。例如:

$result = preg_replace('#\[link\=(.+)\](.+)\[\/link\]#iUs', '<a href="$1">$2</a>', $publishment);

这很好用,因为它返回最终标记。但是,在代码标签中,我需要在数组中包含“属性”和“值”,以便根据这些属性自己构建标记,以便模拟这样的事情:

$code_tag = someFunction("[code ??=?? ...] content [/code]", $array );

//build the markup myself
$attribute1 = array_contains("attribute1", $array)? $array["attribute1"] : "";
echo '<pre {$attribute1}>' . $array['content'] . </pre> 

所以,我不指望你完全为我做这件事,我需要你帮助我走向正确的方向,因为我从来没有使用过正则表达式。

先感谢您

4

1 回答 1

0

我喜欢将 preg_replace_callback 用于此类事情:

function codecb($matches)
{
    $original=$matches[0];
    $parameters=$matches[1];
    $content=$matches[2];
    return "<pre>". $content ."</pre>";
}

preg_replace_callback("#\[code(.*)\](.+)\[\/code\]#iUs", "codecb", $str);

因此,当您[code argA=test argB=test]This is content[/code]在功能“codecb”中使用时,您将拥有:

$original = "[code argA=test argB=test]This is content[/code]"
$parameters = " argA=test argB=test"
$content = "This is content"

并且可以preg_match将论据和return替换为整体。

于 2012-08-22T20:12:21.013 回答