从preg_replace函数中提取var值

时间:2012-08-22 19:38:39

标签: php regex bbcode

我正在尝试模拟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);

这很好,因为它返回最终标记。但是,在代码标记中,我需要在数组中使用“属性”和“值”,以便根据这些属性构建标记myselft,以便模拟这样的某些内容:

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

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

所以,我不希望你完全为我做,我需要你帮助我走向正确的方向,因为我从未使用过正则表达式。

提前谢谢

1 个答案:

答案 0 :(得分: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替换整体。