crunchy crunchy - 1 year ago 117
JSON Question

PHP - strpos() on UTF8-encoded json?

I have the JSON-output

Kirchhellener Stra\u00dfe
.. the
is a UTF8-encoded german letter
..I want to search the output for the word
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
in it?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download