解析字符串php并替换子字符串

Vis*_*shi 2 php regex

我有一个字符串,在PHP中,字符串出现了模式 %%abc%%(some substring)%%xyz%%

主字符串中存在多个这样的子串.这些事件中的每一个都需要用数组中的字符串替换, array('substring1','substring2','substring3','substring4')具体取决于a的响应function()返回1到4之间的整数.

我无法找到一种有效的方法来做到这一点.

Jon*_*Jon 7

这种情况需要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);
Run Code Online (Sandbox Code Playgroud)