str_ireplace用作str_replace [英] str_ireplace works as str_replace
问题描述
我需要用url字符串中的小ascii字符替换所有本地字符(包括大写字母).
I need to replace all local characters (including upper case) with small ascii characters in a url string.
$str = "č-ć-đ-š-ž-Č-Ć-Đ-Š-Ž";
echo str_ireplace(array('č', 'ć', 'đ', 'š', 'ž'), array('c', 'c', 'd', 's', 'z'), $str);
结果-c-c-d-s-z-Č-Ć-Đ-Š-Ž
我预期-c-c-d-s-z-c-c-d-s-z
result - c-c-d-s-z-Č-Ć-Đ-Š-Ž
I expected - c-c-d-s-z-c-c-d-s-z
如何使用str_ireplace()
函数获得预期结果.
How to get expected result using str_ireplace()
function.
推荐答案
大多数PHP 字符串函数以字节序列(即单字节字符(ASCII
))的形式处理字符串.
Most of the PHP string functions handle the strings as sequences of bytes, i.e. single-byte characters (ASCII
).
您要替换包含多字节字符的字符串中的字符.
str_replace()
(有点)有效是因为它不在乎将字符串解释为字符.它用另一个字节序列替换了一个字节序列,仅此而已.在大多数情况下,在使用ASCII
甚至是UTF-8
编码的字符串时,它都不会破坏任何内容(因为UTF-8
的设计方式).但是,使用其他编码可能会产生意想不到的结果.
You want to replace characters in a string that contains multi-byte characters.
str_replace()
(kind of) works because it doesn't care to interpret the strings as characters. It replaces a sequence of bytes with another sequence of bytes and that's all. Most of the times it will not break anything while working with ASCII
or even UTF-8
encoded strings (because the way UTF-8
was designed). However, it can produce unexpected results with other encodings.
当要求处理ASCII
范围之外的字符时,请使用[str_ireplace()](http://php.net/manual/en/function.str-ireplace.php) works the same as
str_replace()`.它的不区分大小写"功能要求将字符串拆分为char并识别小写-大写对.但是,由于它不处理多字节字符,因此无法识别代码大于127的任何字符.
When asked to handle characters outside the ASCII
range, [str_ireplace()](http://php.net/manual/en/function.str-ireplace.php) works the same as
str_replace()`. It's "case insensitive" functionality requires splitting the strings into chars and recognizing the lowercase-uppercase pairs. But since it doesn't handle multi-byte characters it cannot recognize any character whose code is greater than 127.
对于多字节字符串,您应该使用多字节字符串 PHP扩展.
For multi-byte character strings you should use the functions provided by the Multibyte String PHP extension.
它提供的唯一字符串替换功能是 mb_ereg_replace()
(不区分大小写的版本 mb_eregi_replace()
),但它们并不能为您提供太大帮助(因为它们不能用于数组).
The only function it provides for strings replacement is mb_ereg_replace()
(with the case-insensitive version mb_eregi_replace()
) but they don't help you very much (because they don't work with arrays).
If the list of characters you want to replace is fixed, my suggestion is to use str_replace()
with a list of characters that includes both cases:
$str = "č-ć-đ-š-ž-Č-Ć-Đ-Š-Ž";
echo str_replace(
array('č', 'ć', 'đ', 'š', 'ž', 'Č', 'Ć', 'Đ', 'Š', 'Ž'),
array('c', 'c', 'd', 's', 'z', 'c', 'c', 'd', 's', 'z'),
$str
);
这篇关于str_ireplace用作str_replace的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!