字符串替换

时间:2010-08-25 09:24:04

标签: php regex string

例如我有这个字符串:

$test_str = "num Test \n num Hello \n num World";

我需要将这些num - s替换为越来越多的数字。像那样

"1 Test \n 2 Hello \n 3 World"

我怎么能这样做?

4 个答案:

答案 0 :(得分:0)

您可以substr_count执行此操作。 (php doc

然后遍历你的字符串,并使用一个计数器进行重新定位。并加上类似echo str_replace("num", $count, $str)的内容。

答案 1 :(得分:0)

你可以使用preg_replace_callback

$test_str = "num Test \n num Hello \n num World";

function replace_inc( $matches ) {
    static $counter = 0; // start value
    return $counter++;
}

$output = preg_replace_callback( '/num/', 'replace_inc', $test_str );

干杯,
haggi

答案 2 :(得分:0)

此版本适用于任何数量的“num”

<?php
  $num = 2;
  $s = "a num b num c num";

  while(strpos($s, "num") !== false) $s = preg_replace("/num/",$num++,$s,1);

  echo "$s\n";
?>

答案 3 :(得分:0)

变体#1 :PHP 5.3+(匿名函数)

$count=0;
echo preg_replace_callback('/\bnum\b/',
                           function($v){global $count; return ++$count;},
                           $test_str) ;

变体#2 :regex substitiution eval

$count=0;
echo preg_replace('/\bnum\b/e', '++$count', $test_str); 

此致

RBO