user3901528
user3901528

Reputation: 95

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

PHP/CSS find two word in string, change its color for display. Having a problem, can't find its solution, any suggestions? thanks.

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

Upvotes: 1

Views: 282

Answers (2)

user4035
user4035

Reputation: 23749

It doesn't work because you have spaces before and after "=" in your original text:

color = "blue"

And don't have spaces in $find:

color="blue"

To avoid this use regular expression:

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

Output:

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

Upvotes: 1

Sreelal P Mohan
Sreelal P Mohan

Reputation: 313

Try this. I think this will solve your problem

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

Upvotes: 1

Related Questions