Please note that all the discussion about mb_str_replace in the comments is pretty pointless. str_replace works just fine with multibyte strings:
<?php
$string = '漢字はユニコード';
$needle = 'は';
$replace = 'Foo';
echo str_replace($needle, $replace, $string);
// outputs: 漢字Fooユニコード
?>
The usual problem is that the string is evaluated as binary string, meaning PHP is not aware of encodings at all. Problems arise if you are getting a value "from outside" somewhere (database, POST request) and the encoding of the needle and the haystack is not the same. That typically means the source code is not saved in the same encoding as you are receiving "from outside". Therefore the binary representations don't match and nothing happens.
PHP.mk документација
hans at loltek dot net
Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.
Патека
ref.mbstring.php
Локална патека за оваа страница.
Извор
php.net/manual/en
Оригиналниот HTML се реупотребува и локално се стилизира.
Режим
Прокси + превод во позадина
Кодовите, табелите и белешките остануваат читливи во истиот тек.
Референца
ref.mbstring.php
hans at loltek dot net
Референца за `ref.mbstring.php` со подобрена типографија и навигација.
hans at loltek dot net
Пример #7 Повикување метод од кука
Шемите за кодирање на повеќебајтни знаци и нивните поврзани проблеми се прилично сложени и се надвор од опсегот на оваа документација. Ве молиме погледнете ги следните URL-адреси и други ресурси за повеќе информации во врска со овие теми.
-
Материјали за Unicode
-
Информации за јапонски/корејски/кинески знаци
» https://resources.oreilly.com/examples/9781565922242/blob/master/doc/cjk.inf
Содржина
- mb_check_encoding е дизајниран да се справува со кодирања базирани на Unicode како што се UTF-8 и UCS-2 и многу еднобајтни кодирања за погодност (наведени во
- mb_chr — Проверете дали низите се валидни за наведеното кодирање
- mb_convert_case — Врати знак според вредноста на Unicode кодната точка
- mb_convert_encoding — Изврши преклопување на големи/мали букви на низа
- mb_convert_kana — Конвертирај низа од едно кодирање на знаци во друго
- mb_convert_variables — Конвертирај "кана" од друго ("зен-каку", "хан-каку" и повеќе)
- mb_decode_mimeheader — Конвертирај код на знак во променлива(и)
- mb_decode_numericentity — Декодирај низа во поле за MIME заглавје
- mb_detect_encoding — Декодирај HTML нумеричка референца на знак во знак
- mb_detect_order — Откриј кодирање на знак
- mb_encode_mimeheader — Постави/Земи редослед за откривање на кодирање на знак
- mb_encode_numericentity — Кодирај низа за MIME заглавје
- mb_encoding_aliases — Кодирај знак во HTML нумеричка референца на знак
- mb_ereg — Земи алијаси на познат тип на кодирање
- mb_ereg_match — Регуларен израз натпревар со поддршка за повеќебајтни знаци
- mb_ereg_replace — Заменете ја регуларната експресија со поддршка за повеќе бајти
- mb_ereg_replace_callback — Замени регуларен израз со поддршка за повеќе бајти
- mb_ereg_search — Изврши пребарување и замена на регуларен израз со поддршка за повеќе бајти користејќи повикана функција
- mb_ereg_search_getpos — Појавување на регуларен израз со повеќе бајти за претходно дефиниран стринг со повеќе бајти
- mb_ereg_search_getregs — Враќа почетна точка за следното појавување на регуларен израз
- mb_ereg_search_init — Преземи го резултатот од последното појавување на регуларен израз со повеќе бајти
- mb_ereg_search_pos — Постави стринг и регуларен израз за појавување на регуларен израз со повеќе бајти
- mb_ereg_search_regs — Враќа позиција и должина на појавен дел од регуларен израз со повеќе бајти за претходно дефиниран стринг со повеќе бајти
- mb_ereg_search_setpos — Враќа појавен дел од регуларен израз со повеќе бајти
- mb_eregi — Постави почетна точка на следното појавување на регуларен израз
- mb_eregi_replace — Појавување на регуларен израз игнорирајќи го случајот со поддршка за повеќе бајти
- mb_get_info — Замени регуларен израз со поддршка за повеќе бајти игнорирајќи го случајот
- mb_http_input — Земи ги внатрешните поставки на mbstring
- mb_http_output — Откриј го карактерниот кодек на HTTP влез
- mb_internal_encoding — Постави/Земи го карактерниот кодек на HTTP излез
- mb_language — Постави/Земи го внатрешниот карактерен кодек
- mb_lcfirst — Направи го првиот знак од низата со мали букви
- mb_list_encodings — Постави/Земи го тековниот јазик
- mb_ltrim — Отстрани празни места (или други знаци) од почетокот на низата
- mb_ord — Враќа низа од сите поддржани кодеци
- mb_output_handler — Земи го Unicode кодот на карактерот
- mb_parse_str — Функција за повикување претвора карактерен кодек во излезен бафер
- mb_preferred_mime_name — Земи MIME charset стринг
- mb_regex_encoding — Постави/Земи кодирање на карактери за мултибајт регуларни изрази
- mb_regex_set_options — Постави/Земи ги стандардните опции за mbregex функции
- mb_rtrim — Отстрани празни места (или други карактери) од крајот на стринг
- mb_scrub — Замени лошо формирани бајт секвенци со заменски карактер
- mb_send_mail — Испрати кодирана пошта
- mb_split — Подели мултибајт стринг користејќи регуларен израз
- mb_str_pad — Пополни мултибајт стринг до одредена должина со друг мултибајт стринг
- mb_str_split — Даден мултибајт стринг, врати низа од неговите карактери
- mb_strcut — Земи дел од стринг
- mb_strimwidth — Земи скратен стринг со одредена ширина
- mb_stripos — Најди позиција на прво појавување на стринг во друг, нечувствително на големи и мали букви
- mb_stristr — Најди прво појавување на стринг во друг, нечувствително на големи и мали букви
- mb_strlen — Добиј ја должината на стринг
- mb_strpos — Најди позиција на прво појавување на стринг во стринг
- mb_strrchr — Најди последно појавување на карактер во стринг во друг
- mb_strrichr — Најди последно појавување на карактер во стринг во друг, нечувствително на големи и мали букви
- mb_strripos — Најди позиција на последно појавување на стринг во друг, нечувствително на големи и мали букви
- mb_strrpos — Најди позиција на последно појавување на стринг во стринг
- mb_strstr — Најди прво појавување на стринг во друг
- mb_strtolower — Токенизирај низа
- mb_strtoupper — Направи низа со мали букви
- mb_strwidth — Врати ширина на стринг
- mb_substitute_character — Постави/Земи заменски карактер
- mb_substr — Земи дел од стринг
- mb_substr_count — Бинарно безбедно споредување на две низи од офсет, до должина на знаци
- mb_trim — Отстрани празни места (или други знаци) од почетокот и крајот на низата
- mb_ucfirst — Направете го првиот знак од низата со голема буква
Белешки од корисници SPL Итератори
deceze на gmail точка com ¶
пред 13 години
Јуџин Мурај ¶
21 години пред
PHP can input and output Unicode, but a little different from what Microsoft means: when Microsoft says "Unicode", it unexplicitly means little-endian UTF-16 with BOM(FF FE = chr(255).chr(254)), whereas PHP's "UTF-16" means big-endian with BOM. For this reason, PHP does not seem to be able to output Unicode CSV file for Microsoft Excel. Solving this problem is quite simple: just put BOM infront of UTF-16LE string.
Example:
$unicode_str_for_Excel = chr(255).chr(254).mb_convert_encoding( $utf8_str, 'UTF-16LE', 'UTF-8');
mdoocy на u точка washington точка edu ¶
19 години пред
Note that some of the multi-byte functions run in O(n) time, rather than constant time as is the case for their single-byte equivalents. This includes any functionality requiring access at a specific index, since random access is not possible in a string whose number of bytes will not necessarily match the number of characters. Affected functions include: mb_substr(), mb_strstr(), mb_strcut(), mb_strpos(), etc.
mitgath на gmail точка com ¶
пред 16 години
according to:
http://bugs.php.net/bug.php?id=21317
here's missing function
<?php
function mb_str_pad ($input, $pad_length, $pad_string, $pad_style, $encoding="UTF-8") {
return str_pad($input,
strlen($input)-mb_strlen($input,$encoding)+$pad_length, $pad_string, $pad_style);
}
?>
mattr на telebody точка com ¶
пред 11 години
A brief note on Daniel Rhodes' mb_punctuation_trim().
The regular expression modifier u does not mean ungreedy, rather it means the pattern is in UTF-8 encoding. Instead the U modifier should be used to get ungreedy behavior. (I have not otherwise tested his code.)
See http://php.net/manual/en/reference.pcre.pattern.modifiers.php
Анонимен ¶
12 години пред
Yet another single-line mb_trim() function
<?php
function mb_trim($string, $trim_chars = '\s'){
return preg_replace('/^['.$trim_chars.']*(?U)(.*)['.$trim_chars.']*$/u', '\\1',$string);
}
$string = ' "some text." ';
echo mb_trim($string, '\s".');
//some text
?>
roydukkey на roydukkey точка com ¶
пред 16 години
This would be one way to create a multibyte substr_replace function
<?php
function mb_substr_replace($output, $replace, $posOpen, $posClose) {
return mb_substr($output, 0, $posOpen).$replace.mb_substr($output, $posClose+1);
}
?>
treilor на gmail точка com ¶
пред 11 години
A small note for those who will follow rawsrc at gmail dot com's advice: mb_split uses regular expressions, in which case it may make sense to use built-in function mb_ereg_replace.
Бен XO ¶
пред 17 години
PHP5 has no mb_trim(), so here's one I made. It work just as trim(), but with the added bonus of PCRE character classes (including, of course, all the useful Unicode ones such as \pZ).
Unlike other approaches that I've seen to this problem, I wanted to emulate the full functionality of trim() - in particular, the ability to customise the character list.
<?php
/**
* Trim characters from either (or both) ends of a string in a way that is
* multibyte-friendly.
*
* Mostly, this behaves exactly like trim() would: for example supplying 'abc' as
* the charlist will trim all 'a', 'b' and 'c' chars from the string, with, of
* course, the added bonus that you can put unicode characters in the charlist.
*
* We are using a PCRE character-class to do the trimming in a unicode-aware
* way, so we must escape ^, \, - and ] which have special meanings here.
* As you would expect, a single \ in the charlist is interpretted as
* "trim backslashes" (and duly escaped into a double-\ ). Under most circumstances
* you can ignore this detail.
*
* As a bonus, however, we also allow PCRE special character-classes (such as '\s')
* because they can be extremely useful when dealing with UCS. '\pZ', for example,
* matches every 'separator' character defined in Unicode, including non-breaking
* and zero-width spaces.
*
* It doesn't make sense to have two or more of the same character in a character
* class, therefore we interpret a double \ in the character list to mean a
* single \ in the regex, allowing you to safely mix normal characters with PCRE
* special classes.
*
* *Be careful* when using this bonus feature, as PHP also interprets backslashes
* as escape characters before they are even seen by the regex. Therefore, to
* specify '\\s' in the regex (which will be converted to the special character
* class '\s' for trimming), you will usually have to put *4* backslashes in the
* PHP code - as you can see from the default value of $charlist.
*
* @param string
* @param charlist list of characters to remove from the ends of this string.
* @param boolean trim the left?
* @param boolean trim the right?
* @return String
*/
function mb_trim($string, $charlist='\\\\s', $ltrim=true, $rtrim=true)
{
$both_ends = $ltrim && $rtrim;
$char_class_inner = preg_replace(
array( '/[\^\-\]\\\]/S', '/\\\{4}/S' ),
array( '\\\\\\0', '\\' ),
$charlist
);
$work_horse = '[' . $char_class_inner . ']+';
$ltrim && $left_pattern = '^' . $work_horse;
$rtrim && $right_pattern = $work_horse . '$';
if($both_ends)
{
$pattern_middle = $left_pattern . '|' . $right_pattern;
}
elseif($ltrim)
{
$pattern_middle = $left_pattern;
}
else
{
$pattern_middle = $right_pattern;
}
return preg_replace("/$pattern_middle/usSD", '', $string) );
}
?>
Хејли Вотсон ¶
пред 7 години
SOME multibyte encodings can safely be used in str_replace() and the like, others cannot. It's not enough to ensure that all the strings involved use the same encoding: obviously they have to, but it's not enough. It has to be the right sort of encoding.
UTF-8 is one of the safe ones, because it was designed to be unambiguous about where each encoded character begins and ends in the string of bytes that makes up the encoded text. Some encodings are not safe: the last bytes of one character in a text followed by the first bytes of the next character may together make a valid character. str_replace() knows nothing about "characters", "character encodings" or "encoded text". It only knows about the string of bytes. To str_replace(), two adjacent characters with two-byte encodings just looks like a sequence of four bytes and it's not going to know it shouldn't try to match the middle two bytes.
While real-world examples can be found of str_replace() mangling text, it can be illustrated by using the HTML-ENTITIES encoding. It's not one of the safe ones. All of the strings being passed to str_replace() are valid HTML-ENTITIES-encoded text so the "all inputs use the same encoding" rule is satisfied.
The text is "x<y". It is represented by the byte string [78 26 6c 74 3b 79]. Note that the text has three characters, but the string has six bytes.
<?php
$string = 'x<y';
mb_internal_encoding('HTML-ENTITIES');
echo "Text length: ", mb_strlen($string), "\tString length: ", strlen($string), " ... ", $string, "\n";
// Three characters, six bytes; the text reads "x<y".
$newstring = str_replace('l', 'g', $string);
echo "Text length: ", mb_strlen($newstring), "\tString length: ", strlen($newstring), " ... ", $newstring, "\n";
// Three characters, six bytes, but now the text reads "x>y"; the wrong characters have changed.
$newstring = str_replace(';', ':', $string);
echo "Text length: ", mb_strlen($newstring), "\tString length: ", strlen($newstring), " ... ", $newstring, "\n";
// Now even the length of the text is wrong and the text is trashed.
?>
Even though neither 'l' nor ';' appear in the text "x<y", str_replace() still found and changed bytes. In one case, it changed the text to "x>y" and in the other it broke the encoding completely.
One more reason to use UTF-8 if you can, I guess.
php на kamiware точка org ¶
пред 9 години
str_replace is NOT multi-bite safe.
This Ukrainian word gives a bug when used in the next code: відео
$rubishcharacters='[#|\[{}\]´`≠,;.:-\\_<>=*+"\'?()!§$&%';
$searchstring='відео';
$result = str_replace(str_split($rubishcharacters), ' ', $searchstring);
Даниел Роудс ¶
12 години пред
Here's a cheap and cheeky function to remove leading and trailing *punctuation* (or more specifically "non-word characters") from a UTF-8 string in whatever language. (At least it works well enough for Japanese and English.)
/**
* Trim singlebyte and multibyte punctuation from the start and end of a string
*
* @author Daniel Rhodes
* @note we want the first non-word grabbing to be greedy but then
* @note we want the dot-star grabbing (before the last non-word grabbing)
* @note to be ungreedy
*
* @param string $string input string in UTF-8
* @return string as $string but with leading and trailing punctuation removed
*/
function mb_punctuation_trim($string)
{
preg_match('/^[^\w]{0,}(.*?)[^\w]{0,}$/iu', $string, $matches); //case-'i'nsensitive and 'u'ngreedy
if(count($matches) < 2)
{
//some strange error so just return the original input
return $string;
}
return $matches[1];
}
Hope you like it!
abidul точка rmdn на gmail точка com ¶
пред 6 години
Having to migrate to MB functions can be a bit of pain if you have a big project. it took us a while at my company but then we made a small script and explained it in a small blog.
https://link.medium.com/25w1LronCX
which makes it really easy to migrate to mb_ functions.
Петер Кел ¶
20 години пред
UTF-16LE solution for CSV for Excel by Eugene Murai works well:
$unicode_str_for_Excel = chr(255).chr(254).mb_convert_encoding( $utf8_str, 'UTF-16LE', 'UTF-8');
However, then Excel on Mac OS X doesn't identify columns properly and its puts each whole row in its own cell. In order to fix that, use TAB "\\t" character as CSV delimiter rather than comma or colon.
You may also want to use HTTP encoding header, such as
header( "Content-type: application/vnd.ms-excel; charset=UTF-16LE" );
rawsrc на gmail точка com ¶
пред 14 години
Hi,
For those who are looking for mb_str_replace, here's a simple function :
<?php
function mb_str_replace($needle, $replacement, $haystack) {
return implode($replacement, mb_split($needle, $haystack));
}
?>
I haven't found a simpliest way to proceed :-)
pdezwart .at. snocap ¶
19 години пред
If you are trying to emulate the UnicodeEncoding.Unicode.GetBytes() function in .NET, the encoding you want to use is: UCS-2LE
johannesponader на dontspamme точка googlemail точка co ¶
пред 15 години
Please note that when migrating code to handle UTF-8 encoding, not only the functions mentioned here are useful, but also the function htmlentities() has to be changed to htmlentities($var, ENT_COMPAT, "UTF-8") or similar. I didn't scan the manual for it, but there could be some more functions that need adjustments like this.