preg_replace和str_replace,好像不能一起用

preg_replace and str_replace, can't seem to use together

我正在尝试创建带有 [secret] 标签的 BB 代码。 BB代码"redacts" 基于用户级别的文本。但是,我在让它正常工作时遇到了问题。

我当前的代码是:

    $replace = array(" ", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
    $text = preg_replace('#\[secret\](.*?)\[/secret\]#si', '', str_replace($replace, "█", $text));

它为用户杠杆输出:

█████[██████]███████████.[/██████]█████

其中大部分是正确的,但是,它变成了 BB 标签和其他所有不应编辑的内容。

我已经移动了 preg_replace 和 str_replace 的顺序,但无法使其正常工作。

正如我在评论中所说,在将标签传递给正则表达式匹配之前,您还用块替换了标签。这样的事情应该可以解决问题。 preg_replace_callback() works almost the same as preg_replace() 但您可以使用一个函数来说明要用什么替换字符串。

<?php
$string = "Here is a secret: [secret]foo bar baz[/secret]";
$result = preg_replace_callback("/\[secret\](.*?)\[\/secret\]/si", function($matches) {
    return preg_replace("/[\w ]/i", "&#9608;", $matches[1]);
}, $string);
echo $result;

如果将其分解为多个步骤,您会发现原始代码存在问题:

<?php
$replace = array(" ", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
$redacted = str_replace($replace, "&#9608;", $text);
// Clearly, the string "secret" is gone by now, so the regex will never match
$text = preg_replace('#\[secret\](.*?)\[/secret\]#si', '', $redacted);