带有 utf-8 的 php substr() 函数叶子?标记在最后
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9087502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
php substr() function with utf-8 leaves ? marks at the end
提问by Nazar
Here is simple code
这是简单的代码
<?php
$var = "Бензин Офиси А.С. также производит все типы жира и смазок и их побочных продуктов в его смесительных установках нефти машинного масла в Деринце, Измите, Алиага и Измире. У Компании есть 3 885 станций технического обслуживания, включая сжиженный газ (ЛПГ) станции под фирменным знаком Петрогаз, приблизительно 5 000 дилеров, двух смазочных смесительных установок, 12 терминалов, и 26 единиц поставки аэропорта.";
$foo = substr($var,0,142);
echo $foo;
?>
and it outputs something like this:
它输出如下内容:
Бензин Офиси А.С. также производит все типы жира и смазок и их побочных продук?...
Бензин Офиси А.С. также производит все типы жира и смазок и их побочных продук?...
I tried mb_substr() with no luck. How to do this the right way?
我试过 mb_substr() 没有运气。如何以正确的方式做到这一点?
回答by Kai Qing
The comments above are correct so long as you have mbstring enabled on your server.
只要您在服务器上启用了 mbstring,上面的评论就是正确的。
$var = "Бензин Офиси А.С. также производит все типы жира и смазок и их побочных продуктов в его смесительных установках нефти машинного масла в Деринце, Измите, Алиага и Измире. У Компании есть 3 885 станций технического обслуживания, включая сжиженный газ (ЛПГ) станции под фирменным знаком Петрогаз, приблизительно 5 000 дилеров, двух смазочных смесительных установок, 12 терминалов, и 26 единиц поставки аэропорта.";
$foo = mb_substr($var,0,142, "utf-8");
Here's the php docs:
这是 php 文档:
回答by Botir Ziyatov
A proper (logical) alternative for unicode strings;
unicode 字符串的适当(逻辑)替代方案;
<?php
function substr_unicode($str, $s, $l = null) {
return join("", array_slice(
preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY), $s, $l));
}
$str = "Büyük";
$s = 0; // start from "0" (nth) char
$l = 3; // get "3" chars
echo substr($str, $s, $l) ."\n"; // Bü
echo mb_substr($str, $s, $l) ."\n"; // Bü
echo substr_unicode($str, $s, $l); // Büy
?>
Use the PHP: mb_substr - Manual
回答by thwd
PHP5 does not understand UTF-8 natively. It is proposed for PHP6, if it ever comes out.
PHP5 本身不理解 UTF-8。它被提议用于 PHP6,如果它出来的话。
Use the multibyte string functionsto manipulate UTF-8 strings safely.
使用多字节字符串函数安全地操作 UTF-8 字符串。
For instance, mb_substr()
in your case.
例如,mb_substr()
在您的情况下。
回答by caw
If your strings may contain Unicode (multi-byte) characters and you don't want to break these, replace substr
with one of the following two, depending on what you want:
如果您的字符串可能包含 Unicode(多字节)字符并且您不想破坏这些字符,请substr
根据您的需要替换为以下两个之一:
Limit to 142 characters:
限制为142 个字符:
mb_substr($var, 0, 142);
Limit to 142 bytes:
限制为142 字节:
mb_strcut($var, 0, 142);
回答by Guga Nemsitsveridze
If you want to use strlen
function, to calculate length of string, which you want to return and your string $word
has UTF-8
encoding, you have to use mb_strlen()
function:
如果要使用strlen
函数来计算要返回的字符串的长度并且字符串$word
具有UTF-8
编码,则必须使用mb_strlen()
函数:
$foo = mb_substr($word, 0, mb_strlen($word)-1);
$foo = mb_substr($word, 0, mb_strlen($word)-1);
回答by usergio
Never use constant in substr
function for UTF-8
string:
切勿在substr
函数中为UTF-8
字符串使用常量:
$st = substr($text, $beg, 100);
50% chance you will get half of a character at end of the string.
您有 50% 的机会在字符串末尾得到半个字符。
Do it like this:
像这样做:
$postion_degin = strpos($text, $first_symbol);
$postion_end = strpos($text, $last_symbol);
$len = $postion_end - $postion_degin + 1;
$st = substr($text, $postion_degin, $len);
100% safe result.
100% 安全的结果。
No mb_substr
.
没有mb_substr
。
回答by Jodyshop
I hope this solution help you as it helped me a lot.
我希望这个解决方案对你有帮助,因为它对我帮助很大。
<?php
if(mb_strlen($post->post_content,'UTF-8')>200){
$content= str_replace('\n', '', mb_substr(strip_tags($post-> post_content),
0, 200,'UTF-8'));
echo $content.'…';
}else{
echo str_replace('\n', '', strip_tags($post->post_content));
}
?>