替换字符串中的标签,然后检查处理后是否出现新标签。再次运行代码,直到不再有要替换的标签。
$string = '[TAG_A] and [TAG_B] are connected with [TAG_[TAG_A]]';
$search = array(
'[TAG_A]' => 'X',
'[TAG_B]' => 'Y',
'[TAG_X]' => 'Z'
);
$continue = true;
while ($continue) {
foreach ($search as $find => $replace) {
$string = str_replace($find, $replace, $string);
}
$continue = false;
foreach ($search as $find => $replace) {
if (strpos($string, $find) !== false) {
$continue = true;
break;
}
}
}
echo $string; // prints "X and Y are connected with Z"
正则表达式解决方案:
$string = '[TAG_A] and [TAG_B] are connected with [TAG_[TAG_A]]';
$search = array(
'TAG_A' => 'X',
'TAG_B' => 'Y',
'TAG_X' => 'Z'
);
while(preg_match_all('/\[([^\[\]]*?)\]/e', $string, $matches)) {
$string = preg_replace('/\[([^\[\]]*?)\]/e', '$search["$1"]', $string);
}
echo $string;