PHP preg_replace修改

PHP preg_replace modification

我有一个表达式 [text][id] 应该替换为 link <a href='id'>text</a>

解法是(id是整数)

$s = preg_replace("/\[([^\]]+)(\]*)\]\[([0-9]+)\]/","<a href=''></a>",$string);

然而,在某些情况下(不总是!)表达式可能如下

[text][id][type]

在这种情况下应替换为 <a href='id' class='type'>text</a>

想法?

使用preg_replace_callback函数的解决方案:

$str = 'some text [hello][1] some text [there][2][news]';  // exemplary string

$result = preg_replace_callback('/\[([^][]+)\]\[([^][]+)\](?:\[([^][]+)\])?/',function($m){
    $cls = (isset($m[3]))? " class='{$m[3]}'" : "";  // considering `class` attribute
    return "<a href='{$m[2]}'$cls>{$m[1]}</a>";
},$str);

print_r($result);

输出(作为网页源代码):

some text <a href='1'>hello</a> some text <a href='2' class='news'>there</a>

  • (?:\[([^][]+)\])? - 考虑可选的第三个捕获组(对于 class 属性值)