Search code examples
phparraysregexpreg-replacepreg-match

How to call a function inside an array that save matches rules


I'm trying to call a function inside one array but using the matches.

I have a string with text ($text) and 2 arrays.

The array A have rules for find content:

$a=array('rule1', 'rule2', rule3');

The array b have:

$b=array("Rule 1 return the matches: $1 $2 $3", "Rule 2: $1 $2 $3", "Rule 3 $1 $2 $3");

And with a foreach loop, the arrays make the work:

foreach($a AS $key => $val){
    while(preg_match($val, $text)){
        $text = preg_replace($val, $b[$key], $text);
    }
}

Exist a method? for do with the array b:

$b=array("Rule 1 return the matches:".calltofunction("$1$2$3")."", ...

I tried use \1 and $1 for the matches, but when i call to the function every time the function receives the string "$1$2$3" or "\1\2\3" but not the matched values.

Regards!


Solution

  • This seems not possible, the array A that save the rules, yes can be used for save the rules. But for the B is needed make the custom function per each one.

    function Myfunction($text) {
        return preg_replace_callback($a[the num id],
        function($match) {
            return "This return this matches: $match[1] $match[2] $match[3]";
        }
        , $text);
    }