phpstr-replaceutf8-decode

Using str_replace in combination with ut8_decode


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']).'))

Solution

  • 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'] ));