Forum Moderators: coopster
I need one small help.
I wish to change a,s,g,j in certain text to z.
I am using this code.
Is there a simple way, so insteat of four lines i can use one line.
<?php
$st = "example asdfghjkl";
$st = str_replace("a", "z", $st);
$st = str_replace("s", "z", $st);
$st = str_replace("g", "z", $st);
$st = str_replace("j", "z", $st);
echo "$st";
?>
Regards
really sorry, anyway one more issue
if wish to have different results for each variable, can we do it in single line.
<?php
$st = "example asdfghjkl";
$st = str_replace("a", "b", $st);
$st = str_replace("s", "f", $st);
$st = str_replace("g", "t", $st);
$st = str_replace("j", "u", $st);
echo "$st";
?>
// Provides: You should eat pizza, beer, and ice cream every day
$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);
Especially if you are new to a language, shortening code too much will just make it harder to maintain, and more difficult to understand, especially if you need to go back to it in future. (Incidentally, you could fit the first $st on the same line, if you wanted to, dtest ;))
I forget whose anecdote it is, but it goes something like this (help me out with the real source, someone!):
The programming student takes his work to the professor, and tells him that something in his code isn't working.
The professor says "of course it isn't working, there aren't any comments in it!".
code one
// Provides: You should eat pizza, beer, and ice cream every day
$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);
code two
$st = "example asdfghjkl";
$letters = array('a' => 'b', 's' => 'f', 'g' => 't', 'j' => 'u');
foreach ($letters as $match => $replace)
$st = str_replace($match, $replace, $st);
echo $st;
the first code searches your string once and makes replacements
the second does the same thing 4 times
my thought is that making 4 replacements on a single search would take longer than a single replacement per search but the search is what takes the time. So you your first code should be less than 4 times faster than the second.