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?
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.
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With