Home > OS >  PHP str_replace not correctly replacing number to string
PHP str_replace not correctly replacing number to string

Time:10-02

Can someone, please, explain me why php function str_replace not correctly replacing number to string?

$number      =   [1,5,10,15];
$text        =   ["one", "five", "ten", "fifteen"];

$replaced_1  =   str_replace($number, $text, 1); 
$replaced_5  =   str_replace($number, $text, 5); 
$replaced_10  =   str_replace($number, $text, 10);
$replaced_15  =   str_replace($number, $text, 15);

echo $replaced_1."<br>"; // one
echo $replaced_5."<br>"; // five
echo $replaced_10."<br>"; // one0
echo $replaced_15; // onefive

Same result with quotes: $number = ["1","5","10","15"]

CodePudding user response:

Str_replace() function replaces some characters with some other characters in a string.

Do you really have to work with str_replace? otherwise just do it with an array:

$numbers = [
    1 => "one",
    15 => "fifteen",
];

echo $numbers[15];

CodePudding user response:

As written in the documentation:

If search or replace are arrays, their elements are processed first to last.

That means: the first replacement for the input 10 replaces the 1 by one, returning one0. There's nothing more in the first array $number that could match this result to anything

CodePudding user response:

I would probably go with Maik Lowrey's answer, however strtr was made for this. With str_replace the 1 as well as the 1 in 10 and 15 will be replaced. But with strtr:

The longest keys will be tried first. Once a substring has been replaced, its new value will not be searched again.

$replaced_1  =  strtr(1, array_combine($number, $text)); 
$replaced_5  =  strtr(5, array_combine($number, $text)); 
$replaced_10 =  strtr(10, array_combine($number, $text));
$replaced_15 =  strtr(15, array_combine($number, $text));

CodePudding user response:

<?php
$number      =   [1,5,10,15];
$text        =   ["one", "five", "ten", "fifteen"];

$replaced_1  =   str_replace(1,"one",$number[0]); 
$replaced_5  =   str_replace(5, "five",$number[1]); 
$replaced_10  =   str_replace(10,"ten",$number[2]);
$replaced_15  =   str_replace(15,"fifteen",$number[3]);

echo $replaced_1."<br>"; // one
echo $replaced_5."<br>"; // five
echo $replaced_10."<br>"; // ten
echo $replaced_15; // fifteen


?>
  • Related