如何使用php获取字符串的第一个字符包含特殊字符? [英] How to get first character of string contain special characters using php?

查看:62
本文介绍了如何使用php获取字符串的第一个字符包含特殊字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了 string [0] 来缩短并显示用户名/姓氏的第一个字符.在用户名称以ö,ä,ü之类的特殊字符开头之前,它一直很好用.

I used string[0] to shorten and show first character of user names/ lastnames. And it worked great until the user's name is starting with a special character like ö, ä, ü.

例如:

$name = 'über';
echo $name[0];
// echoes nothing

同时我正在使用 mb_substr($ string,0,1).但是我真的很想念 $ name [0] :).它更快,更短.我仍然想知道原因是什么,以及是否有办法将这种语法与特殊字符一起使用.

Meanwhile I am using mb_substr($string, 0, 1) instead. But i really miss $name[0] :). It was much faster and shorter. I still wonder what the reason is and if there is a way to use this syntax with special chars.

推荐答案

字符ü不是单字节字符.这是一个多字节(两个字节)的字符.

The character ü is not a single byte character. It is a multi-byte (two byte) character.

您正在尝试访问字符串的第一个字节,因此它不起作用.正是出于这个原因,已经设计了 mb_substr .

You are trying to access the first byte of the character string, so it doesn't work. Just for this very reason, mb_substr has been designed.

根据字符数执行多字节安全 substr()操作.位置从str的开头算起.第一个字符的位置为0.第二个字符的位置为1,依此类推.

Performs a multi-byte safe substr() operation based on number of characters. Position is counted from the beginning of str. First character's position is 0. Second character position is 1, and so on.

如果您只是尝试执行 $ name [0] ,则它是多字节字符的第一个字符,它只是一个空字符串或一个控制字符,用于显示< u 上方的code> .. .(以它为例,例如 .. + u = ü).

If you are just trying to do the $name[0], it get's the first character of the multi-byte character, which is just an empty string or a control character to display the .. above the u. (take it just for example, like .. + u = ü).

这篇关于如何使用php获取字符串的第一个字符包含特殊字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆