日期:2014-05-17 浏览次数:20515 次
<?php $html = '<ul><li>《mainGood》《mainGood》</li><li>《subGood》《subGood》《subGood》</li></ul>'; echo preg_replace("/(《mainGood》|《subGood》)/eis","foo('$1')",$html); function foo($v){ global $count; if($v=='《mainGood》'){ return 1; }else{ $count++; return $count+1; } } //<ul><li>11</li><li>234</li></ul>
------解决方案--------------------
$num_mainGood = $num_subGood = 0;
echo preg_replace_callback("/(《mainGood》)|(《subGood》)/is", '回调函数', $html);
function 回调函数($r) {
global $num_mainGood, $num_subGood;
if($r[1]) $num_mainGood++;
if($r[2]) $num_subGood++;
//以下写返回内容的代码
}
------解决方案--------------------
[liangdong@bb-browser-test00.vm.baidu.com php_project]$ php main.php <ul><li>a</li><li>bc</li></ul> [liangdong@bb-browser-test00.vm.baidu.com php_project]$ cat main.php <?php $html = <<<EOF <ul><li>《mainGood》</li><li>《subGood》《subGood》</li></ul> EOF; $count = 0; $map = array(0 => 'a', 1 => 'b', 2 => 'c'); $result = preg_replace_callback('/《mainGood》|《subGood》/i', function($match) { global $count; global $map; return $map[$count++]; }, $html); echo $result . PHP_EOL; ?>