用PHP反向字符串 [英] Reverse a string with php
问题描述
我正在尝试找到一种方法来反转字符串,我已经找到了替代方法,但是我想以这种方式在框外思考,而不是使用其他任何人的代码作为替代方法,下面的代码将字符串反转了,但是我不断收到此错误:
I am trying to find a way to reverse a string, I've seen alternatives but i wanted to to it this way thinking outside the box and not using anyone else's code as an alternative, the code below reverses the string but I keep getting this error:
注意:未定义的偏移量:第15行的C:\ wamp \ www \ test \ index.php中的25
Notice: Undefined offset: 25 in C:\wamp\www\test\index.php on line 15
25是要减少的字符串的长度.
25 being the length of the string which is being deincremented.
//error_reporting(NULL);
$string = trim("This is a reversed string");
//find length of string including whitespace
$len =strlen($string);
//slipt sting into an array
$stringExp = str_split($string);
//deincriment string and echo out in reverse
for ($i = $len; $i >=0;$i--)
{
echo $stringExp[$i];
}
预先感谢
推荐答案
正如其他人所说,有strrev()
可以做到这一点.
As others said, there's strrev()
to do this.
如果您想自己构建(用于学习?):问题是您的索引开头太高-长度为25的字符串从0到24进行索引,因此循环必须看起来像这样:
If you want to build it on your own (for learning?): your problem is that you're starting with your index one too high - a string of length 25 is indexed from 0 to 24, so your loop has to look like this:
for ($i = $len - 1; $i >=0;$i--)
{
echo $stringExp[$i];
}
这篇关于用PHP反向字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!