有一个字符串$string = "öşğüçı";
注意最后一个不是i当我想通过echo $string[0]
打印第一个字符时,它什么也不打印。。我知道它们是多字节的。。尽管打印第一个字符可以通过完成
echo $string[0].$string[1]
,但那不是我想要的。。问题是
我如何才能使obove提到的问题只是以低于的方式编程
for($i = 0; $i < sizeof($string); $i++)
echo $string[$i] . " ";
它将打印以下
ö ş ğ ü ç ı
php大师请帮忙。。。
将字符串拆分为字符
$string = "öşğüçı";
preg_match_all('/./u', $string, $m);
$chars = $m[0];
注意正则表达式中的"u"标志
<?php
// inform the browser you are sending text encoded with utf-8
header("Content-type: text/plain; charset=utf-8");
// if you're using a literal string make sure the file
// is saved using utf-8 as encoding
// or if you're getting it from another source make sure
// you get it in utf-8
$string = "öşğüçı";
// if you do not have your string in utf-8
// you need to find out the actual encoding
// and use "iconv" to convert it to utf-8
// process the string using the mb_* functions
// knowing that it is encoded in utf-8 at this point
$encoding = "UTF-8";
for($i = 0; $i < mb_strlen($string, $encoding); $i++) {
echo mb_substr($string, $i, 1, $encoding);
}
当然,如果你喜欢另一种编码(但我不明白为什么;也许只有utf-16(,你可以用你想要的编码替换上面的每个"utf-8"实例,并相应地阅读和使用
UTF-16输出示例(文件/输入以UTF-8编码(
<?php
header("Content-type: text/plain; charset=utf-16");
$string = "öşğüçı";
$string = iconv("UTF-8", "UTF-16", $string);
$encoding = "UTF-16";
for($i = 0; $i < mb_strlen($string, $encoding); $i++) {
echo mb_substr($string, $i, 1, $encoding);
}
在PHP中不能以这种方式处理多字节字符串。如果是固定长度编码,每个字符占用,比如说两个字节,那么一次只需占用两个字节。如果是像UTF-8这样的可变长度编码,则需要使用mb_substr
和mb_strlen
。
我可以推荐每个程序员绝对、积极地需要知道的关于使用文本的编码和字符集的内容吗?它将对此进行更详细的解释。
使用iconv_substr或mb_substr获取字符,使用iconv_strlen
或mb_strlen
获取字符串大小。