I'm looking to store every match found using preg_replace_callback in an array which is to be used at a later point. This is what I have so far and I can't work out what is wrong, currently it is storing the last match found, in both $match[0] and $match[3].
What I am attempting to achieve overall is to replace every match with a hyperlinked number, then print the full text below it. Each number is to be linked to its corresponding text.
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);
You need to put the global
statement inside the function. You also need to push a new element onto the $match
array, not overwrite it. And I doubt you want a space between #ref
and $count
in the href
attribute.
$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);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments