2

在 PHP 中,我有一些字符串标签(伪代码):

[TAG_A]              = X
[TAG_B]              = Y
[TAG_X]              = Z

所以当我在字符串中替换这些标签时:

[TAG_A] and [TAG_B] are connected with [TAG_[TAG_A]]

它应该输出:

X and Y are connected with Z

问题在于嵌套标签。它需要递归,首先替换内部标签。所有可能的标签(及其值)都存储在一个大数组中。

我想要一种替换方法,它不仅使用蛮力通过foreach在标签数组上使用来替换所有标签,而且实际上只在字符串中搜索[]-pairs,然后在标签数组中查找值。

我认为,正则表达式不是正确的方法,但是做这样的事情最有效的方法是什么?

4

1 回答 1

1

替换字符串中的标签,然后检查处理后是否出现新标签。再次运行代码,直到不再有要替换的标签。

$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;
于 2013-02-04T15:41:12.000 回答