我有一个字符串,在 PHP 中,该字符串出现了该模式%%abc%%(some substring)%%xyz%%
在主字符串中多次出现此类子字符串。这些事件中的每一个都需要用数组中的字符串替换,
array('substring1','substring2','substring3','substring4')
具体取决于 a 的响应,function()
它返回一个 1 到 4 之间的整数。
我无法找到一种有效的方法来做到这一点。
这种情况需要preg_replace_callback
:
// Assume this already exists
function mapSubstringToInteger($str) {
return (strlen($str) % 4) + 1;
}
// So you can now write this:
$pattern = '/%%abc%%(.*?)%%xyz%%/';
$replacements = array('r1', 'r2', 'r3', 'r4');
$callback = function($matches) use ($replacements) {
return $replacements[mapSubstringToInteger($matches[1])];
};
preg_replace_callback($pattern, $callback, $input);
使用preg_replace_callback()
,像这样:
preg_replace_callback( '#%%abc%%(.*?)%%xyz%%#', function( $match) {
// Do some logic (with $match) to determine what to replace it with
return 'replacement';
}, $master_string);