基本上就是我要找的就是这个主题的PHP版本: Find, replace, and increment at each occurence of string查找特定字符串,并与增量替换 - PHP
在此先感谢您的帮助!
基本上就是我要找的就是这个主题的PHP版本: Find, replace, and increment at each occurence of string查找特定字符串,并与增量替换 - PHP
在此先感谢您的帮助!
$str = 'a hello a some a';
$i = 0;
while (strpos($str, 'a') !== false)
{
$str = preg_replace('/a/', $i++, $str, 1);
}
echo $str;
嘿,你可以做很多的使用preg_replace函数相同:
$num = 1;
while(strpos($str, $findme) !==) {
preg_replace("/$findme/", $num++, $str, 1);
}
这样做是循环的,虽然只要能找到你的字符串和由$ NUM增量替换它。电贺
如果我正确地理解你的问题......
<?php
//data resides in data.txt
$file = file('data.txt');
//new data will be pushed into here.
$new = array();
//fill up the array
foreach($file as $fK =>$fV) $new[] = (substr($fV, 0, 1)==">")? str_replace("num", $fK/2, $fV) : $fV;
//optionally print it out in the browser.
echo "<pre>";
print_r($new);
echo "</pre>";
//optionally write to file...
$output = fopen("output.txt", 'w');
foreach($new as $n) fwrite($output, $n);
fclose($output);
这里是我的两分钱
function str_replace_once($correct, $wrong, $haystack) {
$wrong_string = '/' . $wrong . '/';
return preg_replace($wrong_string, $correct, $haystack, 1);
}
上述功能是用来替换的字符串occurence只有一次,但你可以自由地编辑该功能以执行每一个其他可能的操作。
preg_replace(array_fill(0, 5, '/'.$findme.'/'), range(1, 5), $string, 1);
例子:
preg_replace(array_fill(0, 5, '/\?/'), range(1, 5), 'a b ? c ? d ? e f g ? h ?', 1);
输出
a b 1 c 2 d 3 e f g 4 h 5
它的工作原理,我们不能做到这一点与str_replace函数? – Poonam 2012-02-14 07:29:42
@Poonam不,因为你不能限制'str_replace'只替换一个实例,并且如果你一次性替换它们,它永远不会增加'$ i' – Joe 2012-02-14 07:31:06