【问题标题】:preg_replace() the same string by increment variable based on occurrences orderpreg_replace() 基于出现顺序的增量变量相同的字符串
【发布时间】:2015-08-01 16:09:49
【问题描述】:

我的字符串:

$string = "figno some text and another figno then last figno";

预期输出

1 some text and another 2 then last 3

我试过了:

preg_match_all("/figno/s",$string,$figmatch);
$figno=0;
for($i=0;$i<count($figmatch[0]);$i++){
    $figno=$figno+1;
    $string=str_replace($figmatch[0][$i],$figno,$string);

}

但它会一次替换所有出现的事件。我也试过preg_replace代替str_replace(),但输出相同

【问题讨论】:

    标签: php regex string str-replace


    【解决方案1】:

    只需使用preg_replace_callback(),它会为您获得的每个匹配项调用匿名函数,然后通过引用传递变量$count 以跟踪匹配项的数量,例如

    <?php
    
        $string = "figno some text and another figno then last figno";
        $count = 1;
        echo preg_replace_callback("/figno/s", function($m)use(&$count){
            return $count++;
        }, $string);
    
    ?>
    

    输出:

    1 some text and another 2 then last 3
    

    【讨论】:

      【解决方案2】:

      使用 preg_replace_callback

      $count = 0;
      preg_replace_callback('/figno/', 'rep_count', $string);
      
      function rep_count($matches) {
        global $count;
        return $count++;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-10-12
        • 1970-01-01
        • 2020-04-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-04
        相关资源
        最近更新 更多