2011-01-29 78 views
0

我想用一個數字替換給定字符串的每個實例。PHP:帶唯一替換的preg_replace

例如:

<?php 

$string = "Hello Foo Text Apple" 
preg_replace($pattern, $pattern.$i++, $string); 

//output  
Hello0 Foo1 Text2 Apple3 

?> 

$模式是一個正則表達式查詢,但是在這種情況下,我已經使用純文本

+0

你想替換或附加數字? – jwerre 2011-01-29 17:20:49

+0

@jwerre:我想追加一個數字/字符串 – Zebra 2011-01-29 17:31:15

回答

1
$string = "Hello Hello Hello Test Hello Test"; 

$i = 0; 
$string = preg_replace("/\w+/e", '$0 . $i++', $string); 
2

如果你正在使用PHP 5.3:

$string = "Hello Hello Hello Hello"; 
$i = 0; 
preg_replace_callback($pattern, function($matches) use ($i) { 
    return $matches[0].$i++; 
}, $string);