简体   繁体   English

PHP - UTF8 编码的 json 上的 strpos()?

[英]PHP - strpos() on UTF8-encoded json?

I have the JSON-output Kirchhellener Stra\ße .. the 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?我有 JSON 输出Kirchhellener Stra\ße .. 是一个 UTF8 编码的德语字母ß ..我想在输出中搜索单词Straße并替换它,但我不知道怎么做?

$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?我怎么能检测到$streetStraße

To work with UTF-8 encoded strings in PHP, you must use mbstring extension.要在 PHP 中使用 UTF-8 编码的字符串,您必须使用mbstring扩展名。 In this case, the function you're looking for is mb_strpos() .在这种情况下,您要查找的函数是mb_strpos()

Or, in this case, you can just use preg_replace() :或者,在这种情况下,您可以只使用preg_replace()

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

The u modifier ensures that UTF-8 encoding is used when matching the string. u修饰符确保在匹配字符串时使用 UTF-8 编码。 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 variant, as json_decode() will convert this literal into the proper UTF-8 character.您也可以跳过变体,因为json_decode()会将此文字转换为正确的 UTF-8 字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM