【问题标题】:Extract var value from preg_replace function从 preg_replace 函数中提取 var 值
【发布时间】:2012-08-22 19:38:38
【问题描述】:

我正在尝试模拟一个 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> 

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

提前谢谢你

【问题讨论】:

  • 仅供参考,如果您使用 # 作为分隔符,则无需在正则表达式中转义 / 字符。
  • @Matt,这些是我以后会记住的一些小笔记。 =)
  • 您可能想先尝试使用preg_match_all($regex, $str, $matches) 解析属性/值对。那么$matches 将是一个包含所有匹配值的数组。
  • @Matt,我已经尝试过您的选择,但是如何删除原始标签并用我的标记替换它? (我的意思是工作流程)

标签: php regex bbcode


【解决方案1】:

我喜欢将 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 替换整个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-24
    • 2011-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多