在PHP中替换模式[关闭]

I have pattern in string to be replaced with something else.

e.g.

$str = '{1} Foo Bar {4}';

I want the above string to be converted like:

$str = arg(0). 'Foo Bar'.arg(4)

Go through this functions

str_replace

preg_replace

for(i=0;i<n;i++){

$str = str_replace("{i}", arg(i), $str);
}

In such cases it's best to use preg_replace_callback(). It's unclear what arg(4) is, variable or real function call.

Only if you can constrain the matched values, you may use preg_replace with /e like that:

 $text = preg_replace('~ [{] (\d+) [}] ~xie', 'arg($1)', $text);

That would invoke arg($decimal) for each occurence of {n}. Workable if you only match decimals like in your example.