使用 PHP 获取字母表中下一个字母的最有效方法
给定从 a 到 z 的任何字符,使用 PHP 获取字母表中下一个字母的最有效方法是什么?
Given any character from a to z, what is the most efficient way to get the next letter in the alphabet using PHP?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
在我看来,最有效的方法是仅增加字符串变量。
如所见,如果您不希望这样,而是想重置以获得
'a'
,则递增'z'
会给出'aa'
可以简单地检查结果字符串的长度以及它的>1
是否重置它。The most efficient way of doing this in my opinion is to just increment the string variable.
As seen incrementing
'z'
give'aa'
if you don't want this but instead want to reset to get an'a'
you can simply check the length of the resulting string and if its>1
reset it.这取决于您按下 Z 时想要执行的操作,但您有几个选择:
您还可以使用 PHP 的
range()
函数:It depends on what you want to do when you hit Z, but you have a few options:
You could also make use of PHP's
range()
function:好吧,这取决于您到底想对“边缘情况”做什么。当字符为
z
或Z
时,您期望什么结果?您想要相同大小写的下一个字母,还是只需要下一个字母、句号?在不知道答案的情况下,对于非常基本的情况,您可以这样做:
但是当您位于
Z
时,这将为您提供[
和z
将为您提供{
(根据 ASCII 值)。根据评论进行编辑:
如果您需要相同大小写的下一个字符,您可能可以在上面的行后面添加简单的检查:
这些都是非常简单的操作,我真的不会担心效率像这样的一个案例。
Well, it depends what exactly you want to do with the "edge cases". What result do you expect when the character is
z
orZ
? Do you want the next letter of the same case, or just the next letter, period?Without knowing the answer to that, for the very basic case, you can just do this:
But when you're at
Z
this will give you[
, andz
will give you{
, according to ASCII values.Edited as per comment:
If you need the next character of the same case, you can probably just add simple checks after the line above:
These are very simple operations, I really wouldn't worry about efficiency in a case like this.
使用 ord() 和 chr() 怎么样?
How about using ord() and chr()?
又好又简单:-)
Nice and easy :-)
由于在这种情况下我只关心小写字符,因此我将根据此处发布的答案使用以下代码:
感谢您的帮助,伙计们!
Since I only care about lowercase characters in this case, I'll use the following code, based on the answers posted here:
Thanks for the help, guys!
创建所有字母的数组,搜索现有字母并返回其下一个字母。如果到达最后一个字母,请返回第一个字母。
Create an array of all letters, search for existing letter and return its next letter. If you reach the last letter return first letter.