Ok if I use the code:
$phrase = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array("fruits", "vegetables", "fiber");
$yummy = array("pizza", "beer", "ice cream");
$newphrase = str_replace($healthy, $yummy, $phrase);
// Provides: You should eat pizza, beer, and ice cream every day
However what if my list of words to replace are a variable.
$sample1 = "fruits, vegetables, fiber";
$sample2 = "pizza, beer, ice cream";
$phrase = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array($sample1);
$yummy = array($sample2);
$newphrase = str_replace($healthy, $yummy, $phrase);
// Provides: You should eat fruits, vegetables, and fiber every day.
Same if I use:
$sample1 = '"fruits", "vegetables", "fiber"';
$sample1 = '"pizza", "beer", "ice cream"';
$phrase = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array($sample1);
$yummy = array($sample2);
$newphrase = str_replace($healthy, $yummy, $phrase);
Am I missing something?
Is there a way to do this easily?
you need to turn the strings in to arrays, use explode in this case:
$sample1 = "fruits, vegetables, fiber";
$sample2 = "pizza, beer, ice cream";
$phrase = "You should eat fruits, vegetables, and fiber every day.";
$healthy = explode(',',$sample1);
$yummy = explode(',',$sample2);
$newphrase = str_replace($healthy, $yummy, $phrase);
You can explode a string
into an array
using a separator:
$sample1 = "fruits, vegetables, fiber";
$sample2 = "pizza, beer, ice cream";
$phrase = "You should eat fruits, vegetables, and fiber every day.";
$healthy = explode(",", $sample1);
$yummy = explode(",", $sample2);
$newphrase = str_replace($healthy, $yummy, $phrase);
I would recommend that you don't have white space between each string though. If you're going to do that then you'll probably want to trim()
each value. array_map()
comes in useful here because you can map a function to every value like this:
$healthy = array_map('trim', explode(",", $sample1));
So the whole thing would be more like:
$sample1 = "fruits , vegetables,fiber";
$sample2 = "pizza, beer,ice cream";
$phrase = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array_map('trim', explode(",", $sample1));
$yummy = array_map('trim', explode(",", $sample2));
$newphrase = str_replace($healthy, $yummy, $phrase);