its*_*zad 9 php string alphabet
$str = 'a';
echo ++$str; // prints 'b'
$str = 'z';
echo ++$str; // prints 'aa'
Run Code Online (Sandbox Code Playgroud)
在excel文件中获取下一个列名非常有用.
但是,如果我使用类似的代码使用 - 运算符来获取前一个字母,那么它不起作用:
$str = 'b';
echo --$str; // prints 'b' but I need 'a'
$str = 'aa';
echo --$str; // prints 'aa' but I need 'z'
Run Code Online (Sandbox Code Playgroud)
什么可以解决前一个字母同样的问题?可能是因为它不起作用的原因是什么?
$str='z';
echo chr(ord($str)-1); //y
Run Code Online (Sandbox Code Playgroud)
注意:这不是循环的a-z.需要为此添加规则
编辑 此编辑涵盖了excel示例中的特殊要求.虽然它的代码有点长.
//Step 1: Build your range; We cant just go about every character in every language.
$x='a';
while($x!='zz') // of course you can take that to zzz or beyond etc
{
$values[]=$x++; // A simple range() call will not work for multiple characters
}
$values[]=$x; // Now this array contains range `a - zz`
//Step 2: Provide reference
$str='ab';
//Step 3: Move next or back
echo $values[array_search(strtolower($str),$values)-1]; // Previous = aa
echo $values[array_search(strtolower($str),$values)+1]; // Next = ac
Run Code Online (Sandbox Code Playgroud)
its*_*zad -1
我可以用这种方法解决。如何?缺点是它现在只能处理大写字母。更多的工作也可以解决这个问题。
<?php
function get_previous_letter($string){
$last = substr($string, -1);
$part=substr($string, 0, -1);
if(strtoupper($last)=='A'){
$l = substr($part, -1);
if($l=='A'){
return substr($part, 0, -1)."Z";
}
return $part.chr(ord($l)-1);
}else{
return $part.chr(ord($last)-1);
}
}
echo get_previous_letter("AAAAAA");
?>
Run Code Online (Sandbox Code Playgroud)