我又一个字符串:
$html = '<ul><li>《mainGood》</li><li>《subGood》《subGood》</li></ul>';//《mainGood》《subGood》个数不定我现在用echo preg_replace("/(《mainGood》)|(《subGood》)/is",回调函数,$html);我本来想用回调函数的方法替换《mainGood》为1,第一个《subGood》为2,第三个《subGood》为3,依次类推,我本来想在回调函数中获取到当前替换的是第几个,然后确定替换内容。但是在回调函数中不知道该怎么写了,请高手帮下忙。

解决方案 »

  1.   

    是这个意思么?<?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>
      

  2.   

    $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++;
      //以下写返回内容的代码}
      

  3.   

    [[email protected] php_project]$ php main.php 
    <ul><li>a</li><li>bc</li></ul>
    [[email protected] 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;
    ?>