Php Preg_replace return$1代替真实内容

Php Preg_replace return$1代替真实内容,php,regex,preg-replace,Php,Regex,Preg Replace,我在一个preg\u replace()中有一个函数 我是这样使用它的: $pattern[] = "/\[test\](.*?)\[\/test\]/is"; $replace[] = $this->test('$1'); $content = preg_replace($pattern, $replace, $content); 然后函数test()打印出发送给它的值。 但值始终仅为$1,而它应该是[test]…[/test]中的内容 你知道怎么做吗?单引号表示文字字符串 因此,“

我在一个
preg\u replace()
中有一个函数

我是这样使用它的:

$pattern[] = "/\[test\](.*?)\[\/test\]/is";
$replace[] = $this->test('$1');

$content = preg_replace($pattern, $replace, $content);
然后函数
test()
打印出发送给它的值。 但值始终仅为
$1
,而它应该是
[test]…[/test]
中的内容


你知道怎么做吗?

单引号表示文字字符串

因此,
“$1”
将返回
$1


“$1”
将把存储在
$1
中的正则表达式捕获值解释为其值

单引号表示文字字符串

因此,
“$1”
将返回
$1

虽然
“$1”
将把存储在
$1
中的正则表达式捕获值解释为其值
test()
将永远不会接收
$1
的值,但它将始终获得文本字符串
“$1”
。当执行
$this->test()
时,调用
test()
函数,它将接收插入括号中作为参数的内容

当执行
test()
时,正则表达式尚未计算。您必须执行以下操作:

$pattern = "/\[test\](.*?)\[\/test\]/is";
$content = $this->test( preg_replace( $pattern, '$1', $content));
这将导致
test()
接收
$1
的值。否则,您需要
preg\u replace\u callback()

test()。当执行
$this->test()
时,调用
test()
函数,它将接收插入括号中作为参数的内容

当执行
test()
时,正则表达式尚未计算。您必须执行以下操作:

$pattern = "/\[test\](.*?)\[\/test\]/is";
$content = $this->test( preg_replace( $pattern, '$1', $content));
这将导致
test()
接收
$1
的值。否则,您需要
preg\u replace\u callback()


如果您希望将匹配项替换为
$this->test
方法的返回值以及第一个子模式的相应匹配字符串,则需要使用
preg\u replace\u callback
和包装函数:

$pattern = "/\[test\](.*?)\[\/test\]/is";
$replace = function($match) use ($this) { return $this->test($match[1]); };
$content = preg_replace_callback($pattern, $replace, $content);

如果您希望将匹配项替换为
$this->test
方法的返回值以及第一个子模式的相应匹配字符串,则需要使用
preg\u replace\u callback
和包装函数:

$pattern = "/\[test\](.*?)\[\/test\]/is";
$replace = function($match) use ($this) { return $this->test($match[1]); };
$content = preg_replace_callback($pattern, $replace, $content);

我想使用单引号是有意的。它应替换为表达式的第一个捕获组的值。无论如何,变量不能以数字开头。是的,第一个捕获组,我想“variable”是一个错误的词。哦,不,在这种情况下,使用单引号或双引号并不重要。我想使用单引号是有意的。它应替换为表达式的第一个捕获组的值。无论如何,变量不能以数字开头。是的,第一个捕获组,我想这里使用的“variable”是错误的词哦,不,在这种情况下,使用单引号还是双引号并不重要。