如何在PHP中找到给定字符串中的回文数?
根据给定的输入查找以下类型的输出如何在PHP中找到给定字符串中的回文数?,php,Php,根据给定的输入查找以下类型的输出 $string = "how are level"; 因此,输出将是 字数:-1&这是一个级别 字数:-2&这是一个级别 因此,它将用它的计数来计算字符串中有多少单词是回文的 我尝试过的示例代码 function checkPalindrome($string){ $reverse = ''; $results = array(); $array = explode(" ",$string); foreach($array a
$string = "how are level";
因此,输出将是
字数:-1&这是一个级别
字数:-2&这是一个级别
因此,它将用它的计数来计算字符串中有多少单词是回文的
我尝试过的示例代码
function checkPalindrome($string){
$reverse = '';
$results = array();
$array = explode(" ",$string);
foreach($array as $word){
$reverse = strrev($word);
if($word == $reverse){
$results[]= $word;
}
}
return $results;
}
$string = "How many level we have level i"; // Input String/Parameter for function
$result = checkPalindrome($string); // Call function
print_r(array_count_values($result));
if(count($result) > 0){
echo "Palindrome word is:";
foreach ($result as $rWord){
echo "<br /><b>".$rWord."</b>";
}
}
如果可以按空间分解,请执行以下操作:
$words = explode(' ', $string);
$count = 0;
foreach($words as $word) {
if(strrev($word) === $word) {
$count++;
}
}
echo $count;
你可能会使用,,,爆炸。还有其他的角色。试试看
<?php
$str="hi helo how wow are you level level";
$word=explode(" ",$str);
$count=0;
foreach($word as $val)
{
if($val==strrev($val))
{
$count++;
}
}
echo $count." time pallindrum found in <br>$str";
?>
使用一个简单的分解并使用strev函数检查和更新计数器缺少$before count变量,但它可以工作!编辑。谢谢
<?php
$str="hi helo how wow are you level level";
$word=explode(" ",$str);
$count=0;
foreach($word as $val)
{
if($val==strrev($val))
{
$count++;
}
}
echo $count." time pallindrum found in <br>$str";
?>