2012-07-16 69 views
2

我有一个字符串,在PHP和该字符串有图案的出现%%abc%%(some substring)%%xyz%%解析通过串php和替换子

有主路线内的这样的子串的多个实例。 每个这些事件的需要与串从根据一个function()其返回到4.

1之间的整数我不能找出一个有效的方式来的响应的阵列 array('substring1','substring2','substring3','substring4')内更换做这个。

回答

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); 
+0

注意$模式是一个正则表达式的字符串,因此,如果你改变$模式确保您转义任何正则表达式字符 – MrGlass 2012-07-16 19:32:34

1

使用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);