我希望将使用preg_replace_callback找到的每个匹配项存储在稍后要使用的数组中。这是我到目前为止所做的,我无法解决出错的问题,目前它正在存储找到的最后一个匹配,在$ match [0]和$ match [3]中。
我试图实现的总体目标是用超链接号码替换每个匹配项,然后打印下面的全文。每个号码都与其相应的文本相关联。
global $match;
$match = array();
$pattern = $regex;
$body = preg_replace_callback($pattern, function($matches){
static $count = 0;
$count ++;
$match = $matches;
return "<a href=\"#ref $count\">$count</a>";
}, $body);
答案 0 :(得分:1)
您需要将global
语句放在函数中。您还需要将新元素推送到$match
数组,而不是覆盖它。我怀疑你想在#ref
属性中$count
和href
之间留一个空格。
$match = array();
$pattern = $regex;
$body = preg_replace_callback($pattern, function($matches){
global $match;
static $count = 0;
$count ++;
$match[] = $matches;
return "<a href=\"#ref$count\">$count</a>";
}, $body);