PHP-preg_replace_回调因子标记而失败
首先,我想道歉,如果有现有的线程,我搜索了很多,但找不到解决方案 所以我有preg_replace_回调函数,它用函数替换字符串中的特定标记 例如:PHP-preg_replace_回调因子标记而失败,php,regex,preg-replace-callback,Php,Regex,Preg Replace Callback,首先,我想道歉,如果有现有的线程,我搜索了很多,但找不到解决方案 所以我有preg_replace_回调函数,它用函数替换字符串中的特定标记 例如: $object = preg_replace_callback('~{FUNC\s+(.+?)}(.+?){/FUNC}~is', function($matches) use ($replace) { list($condition, $function, $content) = $matches; return
$object = preg_replace_callback('~{FUNC\s+(.+?)}(.+?){/FUNC}~is', function($matches) use ($replace)
{
list($condition, $function, $content) = $matches;
return $function($content);
}, $object);
{FUNC name_of_func}
text
text
text
{FUNC name_of_func2}text 2{/FUNC}
text
text
{/FUNC}
但当我在另一个标记中使用sub标记时,它失败了
例如:
$object = preg_replace_callback('~{FUNC\s+(.+?)}(.+?){/FUNC}~is', function($matches) use ($replace)
{
list($condition, $function, $content) = $matches;
return $function($content);
}, $object);
{FUNC name_of_func}
text
text
text
{FUNC name_of_func2}text 2{/FUNC}
text
text
{/FUNC}
我知道它找到了第一个结束标记,这就是问题所在,但我对regex不太了解,如何解决这个问题,以便在可能的情况下使用多个子标记或子子标记?在这里,我们可能希望找到要替换的打开和关闭标记,用
preg\u match\u all
收集它,然后,我们将根据我们的模式将其逐个替换为preg_regplace
,类似于:
$re = '/{FUNC\s+(.+?)}|{\/FUNC}/mi';
$str = '{FUNC name_of_func}
text
text
text
{FUNC name_of_func2}text 2{/FUNC}
text
text
{/FUNC}';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
foreach ($matches as $key => $match) {
if ($match[1] != null) {
$str = preg_replace('/({FUNC\s+)(.+?)(})/is', '$1Another new name that we wish$3', $str);
}
if (preg_match('/{[a-z]/is', $match[0])) {
$str = preg_replace($match[0], '{New_FUNC}', $str);
} elseif (preg_match('/{\//s', $match[0])) {
$str = preg_replace($match[0], '/New_CLOS_FUNC', $str);
} else {
continue;
}
}
var_dump($str);
输出
正则表达式电路
可视化正则表达式:
要使用
preg\u replace\u回调执行最终嵌套结构的自定义替换
一种简单的方法是在循环时先替换最里面的部分,直到没有东西可替换为止。为此,您的模式必须禁止嵌套零件
另外,与其使用list()
不必要地复制匹配数组,不如使用命名捕获:
$replace = [
'func1' => function ($var) { /*...*/ },
'func2' => function ($var) { /*...*/ },
//...
];
$pattern = '~{FUNC \s+ (?<funcName> \w+ )}
(?<content> [^{]*+ (?: { (?!/?FUNC\b) [^{]* )*+ )
{/FUNC}~xi';
do {
$object = preg_replace_callback($pattern, function($m) use ($replace) {
return $replace[$m['funcName']]($m['content']);
}, $object, -1, $count);
} while ($count);
$replace=[
'func1'=>函数($var){/*…*/},
'func2'=>函数($var){/*…*/},
//...
];
$pattern='~{FUNC\s+(?\w+)}
(?[^{]*+(?:{(?!/?FUNC\b)[^{]*)*+)
{/FUNC}~xi';
做{
$object=preg\u replace\u回调($pattern,function($m)use($replace){
返回$replace[$m['funcName']]($m['content']);
},$object,-1,$count);
}而(计算),;
这是因为您的惰性量词在遇到第一个{/FUNC}
时就停止了。当存在嵌套结构时,请使用或同时使用解析器。