Using str_replace in combination with ut8_decode

123 Views Asked by At

To start I am not that experienced in php yet, so I have this code that I did not write myself.

.utf8_decode($var['ciudad']).

It returns a value of a city, this is a number, 66170 or 66001.

What I need is, for it not to return the number but the name of the city. So let´s say the return is ´66170´, it should show ´London´ not the number ´66170´.

Now I know I should use str_replace. But here is where I get stuck, the piece of code has utf8_decode in it which messes with my code. (or just confuses me) my idea was more or less like this:

$ciudad= .utf8_decode(str_replace('66170 ', 'London',($var['ciudad']).'))
2

There are 2 best solutions below

1
HV Sombrilla On BEST ANSWER

Short Answer

What You are trying to do is this

$ciudad = utf8_decode(str_replace('66170', 'London',$var['ciudad'] ));

Removing a dot, a space, some parenthesis and quotes.

Long Answer

I recommend use two arrays. First one with all cities number and the second one with all cities name, then use them as str_replace parameters. Eg:

$citiesCodes = Array(1, 2, 3, 4, ... , 66170); 
$citiesNames = Array('New York', 'Santo Domingo', 'La Paz', 'Lima', ... , 'London'); 


$ciudad = utf8_decode(str_replace($citiesCodes, $citiesNames, $var['ciudad'] ));
2
kay27 On

Your idea was right. The only thing you've missed is that you first of all need to decode it:

$ciudad = str_replace('66170', 'London', utf8_decode($var['ciudad']));

If you have many city codes, it's better to use strtr(). I've updated my suggestion according your last comment:

$cities = Array(
  '66170' => 'London',
  '66001' => 'New York',
  '66002' => 'Beijing',
);

$ciudad = strtr($var['ciudad'], $cities);