,比如我有这个字符串:字符串替换
$test_str = "num Test \n num Hello \n num World";
,我需要更换这些num
-s来越来越多。这样
"1 Test \n 2 Hello \n 3 World"
我怎么能这样做?
,比如我有这个字符串:字符串替换
$test_str = "num Test \n num Hello \n num World";
,我需要更换这些num
-s来越来越多。这样
"1 Test \n 2 Hello \n 3 World"
我怎么能这样做?
你可以使用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
此版本适用于任何数量的“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
五月我请你在这里描述一个真实的案例,不是过分简化了一个? – 2010-08-25 09:26:54