2012-02-14 48 views

回答

1
$str = 'a hello a some a'; 
$i = 0; 

while (strpos($str, 'a') !== false) 
{ 
    $str = preg_replace('/a/', $i++, $str, 1); 
} 

echo $str; 
+0

它的工作原理,我们不能做到这一点与str_replace函数? – Poonam 2012-02-14 07:29:42

+0

@Poonam不,因为你不能限制'str_replace'只替换一个实例,并且如果你一次性替换它们,它永远不会增加'$ i' – Joe 2012-02-14 07:31:06

-1

嘿,你可以做很多的使用preg_replace函数相同:

$num = 1; 
while(strpos($str, $findme) !==) { 
preg_replace("/$findme/", $num++, $str, 1); 
} 

这样做是循环的,虽然只要能找到你的字符串和由$ NUM增量替换它。电贺

+0

你的正则表达式会从字面上搜索''findme'''。你可以用双引号括起来:'“/ $ findme /”'或者将它连接到:''/'。 $ findme。 '/'' – Joe 2012-02-14 07:31:54

+0

谢谢乔。编辑它。 (想用双引号) – CyrillC 2012-02-14 07:39:16

+0

这段代码什么都不会做。正确的是'$ str = preg_replace(“/ $ findme /”,$ num ++,$ str,1);' – va5ja 2014-03-25 09:36:14

0

如果我正确地理解你的问题......

<?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); 
-1

这里是我的两分钱

function str_replace_once($correct, $wrong, $haystack) { 
    $wrong_string = '/' . $wrong . '/'; 
    return preg_replace($wrong_string, $correct, $haystack, 1); 
} 

上述功能是用来替换的字符串occurence只有一次,但你可以自由地编辑该功能以执行每一个其他可能的操作。

0
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