解析字符串 php 并替换子字符串
我有一个字符串,在 PHP 中,该字符串出现了 %%abc%%(some substring)%%xyz%%
I have a string, in PHP and the string has occurrences of the pattern %%abc%%(some substring)%%xyz%%
在主字符串中多次出现此类子字符串.这些出现中的每一个都需要用数组中的字符串替换array('substring1','substring2','substring3','substring4')
取决于 function()
的响应,它返回 1 到 4 之间的整数.
There are multiple occurrences of such substrings within the master string.
Each of these occurrences need to be replaced with a string from within an array
array('substring1','substring2','substring3','substring4')
depending upon the response of a function()
which returns back a integer between 1 to 4.
我无法找到一种有效的方法来做到这一点.
I am not able to figure out an efficient way to do this.
这种情况需要 preg_replace_callback
:
This is a situation that calls for 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);