如何在PHP中找到给定字符串中的回文数?

时间:2016-05-27 14:56:26

标签: php

根据给定输入查找以下类型的输出

$string = "how are level";

所以输出将是

  

字数: - 1&它"等级"。

$string = "how are level level"; 
  

字数: - 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>";
    }
}

2 个答案:

答案 0 :(得分:3)

如果可以按空间爆炸,请执行以下操作:

$words = explode(' ', $string);
$count = 0;

foreach($words as $word) {
    if(strrev($word) === $word) {
        $count++;
    }
}

echo $count;

你可能会爆炸使用&#34;,&#34;,&#34;。&#34;和其他人。

答案 1 :(得分:0)

试试吧

<?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";
?>