crunchy crunchy - 1 month ago 16
JSON Question

PHP - strpos() on UTF8-encoded json?

I have the JSON-output

Kirchhellener Stra\u00dfe
.. the
\u00df
is a UTF8-encoded german letter
ß
..I want to search the output for the word
Straße
and replace it, but I can't figure out how?

$street = json_decode($bit->long_name); // here the `Kirchhellener Stra\u00dfe` is put into $street

$check_strasse1 = strpos($street, 'Straße');
$check_strasse2 = strpos($street, 'Stra\u00dfe');

if($check_strasse1 !== false || $check_strasse2 !== false) {
echo "oki";
$street = str_replace('Strasse', 'Str.', $street);
$street = str_replace('Stra\u00dfe', 'Str.', $street);
} else {
echo "nope";
}


How can I detect it the
$street
has
Straße
in it?

Answer

To work with UTF-8 encoded strings in PHP, you must use mbstring extension. In this case, the function you're looking for is mb_strpos().

Or, in this case, you can just use preg_replace():

preg_replace('/Straße/u', 'Str.', $street);

The u modifier ensures that UTF-8 encoding is used when matching the string. You don't need to check if the string is present, because if it's not, it will not be replaced. You can also skip the \u00df variant, as json_decode() will convert this literal into the proper UTF-8 character.

Comments