如何在保存匹配规则的数组中调用函数

时间:2015-07-02 00:27:47

标签: php arrays regex preg-replace preg-match

我正在尝试在一个数组中调用一个函数但是使用匹配。

我有一个包含文本($ text)和2个数组的字符串。

数组A具有查找内容的规则:

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

数组b有:

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

使用foreach循环,数组可以完成工作:

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

存在一种方法?对于数组b:

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

我尝试使用\ 1和$ 1进行匹配,但是每当函数收到字符串“$ 1 $ 2 $ 3”或“\ 1 \ 2 \ 3”而不是匹配的值时,我会调用该函数。

问候!

1 个答案:

答案 0 :(得分:0)

这似乎不可能,保存规则的数组A,是可以用来保存规则。但是因为需要B来制作每个人的自定义功能。

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