Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

str_replace with array

I'm having some troubles with the PHP function str_replace when using arrays.

I have this message:

$message = strtolower("L rzzo rwldd ty esp mtdsza'd szdepw ty esp opgtw'd dple"); 

And I am trying to use str_replace like this:

$new_message = str_replace(     array('l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','a','b','c','d','e','f','g','h','i','j','k'),     array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'),     $message); 

The result should be A good glass in the bishop's hostel in the devil's seat, but instead, I get p voos vlpss xn twt qxswop's wosttl xn twt stvxl's stpt.

However, when I only try replacing 2 letters it replaces them well:

$new_message = str_replace(array('l','p'), array('a','e'), $message); 

the letters l and p will be replaced by a and e.

Why is it not working with the full alphabet array if they are both exactly the same size?

like image 630
LautaroAngelico Avatar asked Dec 05 '12 03:12

LautaroAngelico


People also ask

How can I replace part of a string in PHP?

The str_replace() is a built-in function in PHP and is used to replace all the occurrences of the search string or array of search strings by replacement string or array of replacement strings in the given string or array respectively.

How can I replace multiple characters in a string in PHP?

Approach 1: Using the str_replace() and str_split() functions in PHP. The str_replace() function is used to replace multiple characters in a string and it takes in three parameters. The first parameter is the array of characters to replace.

How do I remove a word from a string in PHP?

Answer: Use the PHP str_replace() function You can use the PHP str_replace() function to replace all the occurrences of a word within a string.

What is use of Preg_replace in PHP?

PHP | preg_replace() Function The preg_replace() function is an inbuilt function in PHP which is used to perform a regular expression for search and replace the content.


1 Answers

Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements.

     // 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); 
like image 106
Rakesh Tembhurne Avatar answered Oct 08 '22 20:10

Rakesh Tembhurne