0

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);

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

6 Comments

This doesn't seem to change anything, print_r($match) still outputs the same as I mentioned originally. For reference i am calling print_r just after the code above.
You were overwriting $match instead of adding a new element.
Just saw that you added [] to $match, now it seems to be putting too much into the array. Array ( [0] => Array ( [0] => match1 [1] => [2] => [3] => match1 ) This is the output for each match, how would I reduce this?
I just fixed this myself, I changed $matches; to $matches[0]; Thanks for the help!
$matches is an array where $matches[0] is the match for the entire regexp, $matches[1] is the match for the first capture group, and so on. If you don't want all the capture groups, push what you want, e.g. $matches[0] onto $match. It's not clear from the question exactly what you're trying to collect into $match. Surely you can take the basic structure of the answer and fit it to your actual needs.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.