PHP/CSS在字符串中找到两个颜色的单词,改变它的颜色


PHP/CSS find two color word in string, change its color

PHP/CSS在字符串中找到两个单词,更改其显示颜色。遇到问题,找不到解决方法,有什么建议吗?谢谢。

<?php
$word = '<font color = "blue">blue</font>';
$num = '<font color = "blue">123</font>';
$text = $word.$num;
echo '$text='.$text.'<br>';
$blue='blue';
$find = '<font color="blue">'.$blue.'</font>';
$re='<font color="green">'.$blue.'</font>';
$check = str_replace($find,$re,$text);
echo '$find='.$find.'<br>';
echo '$re='.$re.'<br>';
echo '$check='.$check.'<br>';
?>

它不起作用,因为在原始文本中"="前后有空格:

color = "blue"

并且$find:

中不要有空格
color="blue"

要避免这种情况,使用正则表达式:

<?php
$word = '<font color = "blue">blue</font>';
$num = '<font color = "blue">123</font>';
$text = $word.$num;
$blue='blue';
$find = '<font color.*?=.*?"blue">'.$blue.'<'/font>';
$re='<font color="green">'.$blue.'</font>';
$check = preg_replace("/$find/", $re, $text);
echo '$check='.$check."<br>'n";
?>
输出:

$check=<font color="green">blue</font><font color = "blue">123</font><br>

试试这个。我想这会解决你的问题。

<?php
$word = '<font color = "blue">blue</font>';
$num = '<font color = "blue">123</font>';
$text = $word.$num;
echo $text.'='.$text.'<br>';
$blue='blue';
$find = '<font color="blue">'.$blue.'</font>';
$re='<font color="green">'.$blue.'</font>';
$check = str_replace($find,$re,$text);
echo $find.'='.$find.'<br>';
echo $re.'='.$re.'<br>';
echo $check.'='.$check.'<br>';
?>