2010-07-11 69 views
4

我需要用「test(Z)」代替「{Z}」,其中Z總是使用PHP和正則表達式的無符號整數(除非有更快的方法?)。正則表達式匹配「{number}」

$code='{45} == {2}->val() - {5}->val()'; 
// apply regex to $code 
echo $code; 
// writes: test(45) == test(2)->val() - test(5)->val() 

棘手的部分是,它需要以最好的方式完成速度和內存使用。

回答

8

的缺失行是這樣的:

$code = preg_replace('/{([0-9]+)}/', 'test($1)', $code); 

它是如何工作的:

 
{  match a literal { 
(  start a capturing group 
[0-9]+ one or more digits in 0-9 
)  end the capturing group 
}  match a literal } 

在替換字符串中的$ 1指由第一個(也是唯一一個)捕獲組捕獲的字符串。

+4

使用'\ d';讓我們不要開始教壞習慣。 – amphetamachine 2010-07-11 23:35:08

+0

這一個似乎完美的工作。 – Christian 2010-07-11 23:46:21

+1

@amphetamachine:我想說,如果你實際上是指0-9中的數字,那麼你應該寫'[0-9]'。這很清楚你只對那些特定的數字感興趣,而不是其他可以被解釋爲數字的其他字符。在這種情況下,這並沒有太大的區別,但我不明白爲什麼顯性是一種「壞習慣」。也許你可以解釋你的推理? – 2010-07-11 23:53:22

5
$code = preg_replace('/\{(\d+)\}/', 'test($1)', $code); 

根據我的經驗,preg_replace比使用str_replacestrtr做取代的任意方法快