预匹配回调不起作用
Preg match callback not working
我正在尝试编写一个函数来替换任何以 PID 开头和结尾的数字。我认为问题出在正则表达式中,但我无法弄清楚。代码如下。我也试过 (.) 而不是 (.*) - 没有区别。我知道我将不得不遍历 matches 数组以获取所有匹配项,但我想先让基本代码工作。有人能指出问题吗?
function DoLinks($matches) {
return ($matches[0]='<a href="someplace.com">Some place</a>');
}
function Buildinks($text) {
preg_replace_callback(
"/PID(.*)PID/",
"DoLinks",
$text);
return $text;
}
$text = "hello PID(199)PID";
$text = Buildinks($text);
echo $text;
函数 preg_replace_callback return 是一个值,您可以在 Buildinks 函数中 return。
并且 $matches[0]=
可以在 DoLinks 中删除。
正则表达式现在有惰性匹配 .*?
。
以防万一您收到超过 1 个 PID 的文本。
<?php
function DoLinks($matches) {
$pid = $matches[1];
return '<a href="someplace.com">Some place with pid '.$pid.'</a>';
}
function Buildinks($text) {
return preg_replace_callback('/PID\((.*?)\)PID/', 'DoLinks', $text);
}
$text = "hello PID(199)PID and hello PID(200)PID";
$text = Buildinks($text);
echo $text;
我正在尝试编写一个函数来替换任何以 PID 开头和结尾的数字。我认为问题出在正则表达式中,但我无法弄清楚。代码如下。我也试过 (.) 而不是 (.*) - 没有区别。我知道我将不得不遍历 matches 数组以获取所有匹配项,但我想先让基本代码工作。有人能指出问题吗?
function DoLinks($matches) {
return ($matches[0]='<a href="someplace.com">Some place</a>');
}
function Buildinks($text) {
preg_replace_callback(
"/PID(.*)PID/",
"DoLinks",
$text);
return $text;
}
$text = "hello PID(199)PID";
$text = Buildinks($text);
echo $text;
函数 preg_replace_callback return 是一个值,您可以在 Buildinks 函数中 return。
并且 $matches[0]=
可以在 DoLinks 中删除。
正则表达式现在有惰性匹配 .*?
。
以防万一您收到超过 1 个 PID 的文本。
<?php
function DoLinks($matches) {
$pid = $matches[1];
return '<a href="someplace.com">Some place with pid '.$pid.'</a>';
}
function Buildinks($text) {
return preg_replace_callback('/PID\((.*?)\)PID/', 'DoLinks', $text);
}
$text = "hello PID(199)PID and hello PID(200)PID";
$text = Buildinks($text);
echo $text;