我在PHP中的代码 - :如何知道比赛计数preg_replace_callback - PHP
function pregRepler($matches)
{
* do something
}
$str = preg_replace_callback($reg_exp,'pregRepler',$str);
当功能pregRepler
,我想知道当前match number
一样,如果它是第一个匹配或第二或其他什么...
我该怎么做。
我在PHP中的代码 - :如何知道比赛计数preg_replace_callback - PHP
function pregRepler($matches)
{
* do something
}
$str = preg_replace_callback($reg_exp,'pregRepler',$str);
当功能pregRepler
,我想知道当前match number
一样,如果它是第一个匹配或第二或其他什么...
我该怎么做。
尝试这样:
function pregRepler($matches) {
static $matchcount = 0;
// do stuff
$matchcount++;
}
这与匿名函数工作得更好,因为我在my answer提到your other question,因为这将避免出现问题,如果你有preg_replace_callback
多次调用。
$repled = 0;
function pregRepler($matches)
{
* do something
global $repled;
$repled++;
}
$str = preg_replace_callback($reg_exp,'pregRepler',$str);
只计算一个全局变量。
需要通过使用可变别名共享两个可变范围之间的$count
可变的,例如:
$callback = function($matches) use (&$count) {
$count++;
return sprintf("<%d:%s>", $count, $matches[0]);
};
echo preg_replace_callback($pattern, $callback , $subject, $limit = -1, $count);
调用之前,$count
等于0调用$count
被设置为替换数后完成。在两者之间,你可以在你的回调中算数。再次打电话时,您也可以再次设置为零。
非常感谢Kolink ...真的感谢的人 – sanchitkhanna26 2013-04-10 20:30:11
@Kolink你不应该定义函数外的静态?这会不会在每次通话中将$ matchcount重置为0? – 2013-04-10 20:39:03
@ nl-x不,变量是静态的,所以它只会被定义和初始化一次。 – nickb 2013-04-10 20:48:20