php中preg_replace的问题-html中特定于转换的代码

php中preg_replace的问题-html中特定于转换的代码,php,preg-replace,Php,Preg Replace,我试图改变这一点: §f§lWORDHERE 在这方面: <span style="color: white;><b>WORDHERE</b></span> 提前感谢您的regexp只匹配前缀,而不是它后面的单词。你需要一个单词的捕获组 $colorcodes = array( '/§f(\w+)/', '/§l(\w+)/' ); $replacement = array( '<span style=

我试图改变这一点:

§f§lWORDHERE
在这方面:

<span style="color: white;><b>WORDHERE</b></span>

提前感谢

您的regexp只匹配前缀,而不是它后面的单词。你需要一个单词的捕获组

$colorcodes = array(
    '/§f(\w+)/',
    '/§l(\w+)/'
);

$replacement = array(
    '<span style="color: white;">$1</span>',
    '<b>$1</b>',
);
$colorcodes=数组(
“/§f(\w+/”,
“/§l(\w+)/”
);
$replacement=数组(
'$1',
'$1',
);

我将首先捕获标志,然后替换它们:

$str = '§f§lWORDHERE';

$replacements = [
  '§f' => '<span style="color: white;">$0</span>',
  '§l' => '<b>$0</b>',
];

if (preg_match('/^(?<flags>(?:§[a-z])+)(?<string>.*)/iu', $str, $matches)) {
    $str_res = $matches['string'];

    foreach (mb_str_split($matches['flags'], 2) as $flag) {
        $str_res = preg_replace('/.+/', $replacements[$flag], $str_res);
    }

    echo $str_res;
}
可替换为:

str_split($matches['flags'], 3)

如果您使用的是PHP<7.4.

您的输出在哪里?@GetSet§f§l单词抱歉,我在第二个单词中遗漏了
+
。你没注意到区别吗?
$str = '§f§lWORDHERE';

$replacements = [
  '§f' => '<span style="color: white;">$0</span>',
  '§l' => '<b>$0</b>',
];

if (preg_match('/^(?<flags>(?:§[a-z])+)(?<string>.*)/iu', $str, $matches)) {
    $str_res = $matches['string'];

    foreach (mb_str_split($matches['flags'], 2) as $flag) {
        $str_res = preg_replace('/.+/', $replacements[$flag], $str_res);
    }

    echo $str_res;
}
mb_str_split($matches['flags'], 2) 
str_split($matches['flags'], 3)