Is there any possibility to use str_replace
for multiple value replacement in a single line. For example i want to replace \' \'
with \'-\'
$name = abcd;
I want to replace 'a' with '$' and 'b' with '!', so I need to write like this:
$str = ['a','b'];
$rplc =['$','!'];
echo str_replace("$str","$rplc",$name);
output : $!cd
Yes with the help of str_replace function we can do multiple value replacement in a single line without array.Here is my code
echo str_replace(" ","-",str_replace("&","","I like Tea&Coffee"));
str_replace() accepts arrays as arguments.
For example:
$subject = 'milk is white and contains sugar';
str_replace(array('sugar', 'milk'), array('sweet', 'white'), $subject);
In fact, the third argument can also be an array, so you can make multiple replacements in multiple values with a single str_replace()
call.
For example:
$subject = array('milk contains sugar', 'sugar is white', 'sweet as sugar');
str_replace(array('sugar', 'milk'), array('sweet', 'white'), $subject);
As others have noted, this is clearly stated in the manual:
search The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.
replace The replacement value that replaces found search values. An array may be used to designate multiple replacements.
subject The string or array being searched and replaced on, otherwise known as the haystack.
Take note of the order of the arrays as it corresponds to the order.
Like for below, A is replaced with B, B with C and so on.. so there you go.
// Outputs F because A is replaced with B, then B is replaced with C, and so on...
// Finally E is replaced with F, because of left to right replacements.
$search = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'A';
echo str_replace($search, $replace, $subject);
// Outputs: apearpearle pear
// For the same reason mentioned above
$letters = array('a', 'p');
$fruit = array('apple', 'pear');
$text = 'a p';
$output = str_replace($letters, $fruit, $text);
echo $output;
?>
source: PHP str_replace
This is how I did it to replace ' to '' so it doesn't break in SQL queries and " " with "" because people kept adding a space at the end of their emails:
$check = str_replace("'","''",$_POST['1']);
$checkbox1 = str_replace(" ","",$check);
For yours you could do this:
$check = str_replace("&","",$_POST['1']);
$checkbox1 = str_replace(" ","-",$check);
str_replace([' ','-','&'],'',$text);