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

时间:2015-07-12 06:01:12

标签: php css

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>';
?>

2 个答案:

答案 0 :(得分:1)

试试这个。我认为这将解决您的问题

<?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>';
?>

答案 1 :(得分:1)

它不起作用,因为原始文本中“=”之前和之后都有空格:

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>
相关问题