我正在尝试更改子字符串的颜色,如下所示:
$str = 'abcd<efgh>lmno';
preg_match_all('/<[\S]*?>/m', $str, $matches, PREG_PATTERN_ORDER);
$replacements = $needles = [];
foreach ($matches[0] as $match) {
$needles[] = $match;
$replacements[] = '<span style="color:red;">' . $match . '</span>';
}
echo str_replace($needles, $replacements, $str);
我希望得到以下结果:abcd<span style="color:red;"><efgh></span>lmno
但我得到:abcdlmno
答案 0 :(得分:0)
尝试一下:
$str = 'abcd<efgh>lmno';
preg_match_all('/<[\S]*?>/m', $str, $matches, PREG_PATTERN_ORDER);
foreach ($matches[0] as $match) {
$str = str_replace($match, '<span style="color:red;">' . $match . '</span>', $str);
}
echo $str;
//abcd<span style="color:red;"><efgh></span>lmnoC