Home > Software design >  How to change a text in PHP?
How to change a text in PHP?

Time:02-21

I'm trying to change the name of three attributes using a string in PHP, but I'm stuck. Could you help me?

This is the code that I had:

function color () {
    switch ($color) {
    case "red":
        echo "purple";
        break;
    case "yellow":
        echo "yellow brown";
        break;
    case "brown":
        echo "chocolate";
        break;
    }
}

Also, I was trying using the same with a string but I'm not sure if it's okey:

<?php

$color = "'red', 'yellow', 'brown', 'pizza', 'moustard', 'mango', 'lemon'"; 

$searchColor = array ('red','yellow', 'brown');

$replacements = array ( 'purple', 'yellow brown','chocolate');

echo str_replace( $searchColor, $replacements, $color );

?>

CodePudding user response:

However this would work, because this also includes the single quotes in the checking and replacing, so the yellow does not get processed twice

$searchColor = array ("'red'", "'brown'", "'yellow'");
$replacements = array ( "'purple'", "'chocolate'", "'yellow brown'");
echo str_replace( $searchColor, $replacements, $color);

RESULT

'purple', 'yellow brown', 'chocolate', 'pizza', 'moustard', 'mango', 'lemon'
  • Related