我怎样才能在php中使用python的“For loop”来反转字符串?

时间:2013-03-25 10:12:21

标签: php python loops

这是python代码:

def is_palindrome(s):
    return revers(s) == s

def revers(s):
    ret = ''
    for ch in s:
        ret = ch + ret
    return ret

print is_palindrome('RACECAR') 
# that will print true

当我将该函数转换为php。

function is_palindrome($string){
    if (strrev($string) == $string) return true;
    return false;
}
$word = "RACECAR";
var_dump(is_palindrome($word));
// true 

这两个函数都运行正常但是,如何在循环中用php反转字符串?

$string = str_split(hello);
$output = '';
foreach($string as $c){
        $output .= $c;
}
print $output;
// output 
hello 
//i did this,

这是找不到的工作,但有没有办法以更好的方式做到这一点?     $ string =“你好”;     $ lent = strlen($ string);

$ret = '';
for($i = $lent; ($i > 0) or ($i == 0); $i--)
{
    $ret .= $string[$i];
    #$lent = $lent - 1;
}

print $output;
//output 
olleh

4 个答案:

答案 0 :(得分:2)

替换

$output .= $c;

$output = $c . $output;

答案 1 :(得分:1)

我想不能更短。循环:)

$word = "Hello";

$result = '';
foreach($word as $letter)
    $result = $letter . $result;

echo $result;

答案 2 :(得分:0)

我不尝试该代码,但我认为它应该有效:

$string = "hello";
$output = "";
$arr = array_reverse(str_split($string)); // Transform "" to [] and then reverse => ["o","l","l,"e","h"]
foreach($arr as $char) {
    $output .= $char;
}

echo $output;

另一种方式:

$string = "hello";
$output = "";
for($i = strlen($string); $i >= 0; $i--) {
    $output .= substr($string, $i, 1);
}
echo $output;

答案 3 :(得分:-1)

strrev()是一个在PHP中反转字符串的函数。 http://php.net/manual/en/function.strrev.php

$s = "foobar";
echo strrev($s); //raboof

如果你想检查一个单词是否是回文:

function is_palindrome($word){ return strrev($word) == $word }

$s = "RACECAR";
echo $s." is ".((is_palindrome($s))?"":"NOT ")."a palindrome";