字符串替换

问题描述:

,比如我有这个字符串:字符串替换

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

,我需要更换这些num -s来越来越多。这样

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

我怎么能这样做?

+0

五月我请你在这里描述一个真实的案例,不是过分简化了一个? – 2010-08-25 09:26:54

你可以使用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

+0

这正是我需要的 – nukl 2010-08-25 09:42:19

+0

你的例子会将数字返回1,对吧? (0,1,2)为了正确回答,你应该修改你的函数返回++ $ counter或者以$ counter = 1开始 – 2010-08-25 09:54:12

+0

我认为调整“// start value”应该很容易;) 当然,你也可以使用前缀增量这是顺便说一句。一般来说速度更快,但对于那些没有太多进入编程的人来说,这可能会有点混乱 – haggi 2010-08-25 10:08:21

你可以通过substr_count来做到这一点。 (php doc

然后依次通过您的字符串,并使用一个计数器为recplace。并把类似echo str_replace("num", $count, $str)

+0

嗯,我也可以通过substr_count来计算'num'-s。但是str_replace会替换'$ str'中的所有'num'-s,所以有什么意义?或者我只是不明白吗? – nukl 2010-08-25 09:45:37

此版本适用于任何数量的“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"; 
?> 

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

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

变体#2:正则表达式substitiution EVAL

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

问候

RBO