A palindrome is a word or phrase that is identical forward or backward, such as
ID: 3782252 • Letter: A
Question
A palindrome is a word or phrase that is identical forward or backward, such as the word “racecar.” A standard palindrome is similar to a perfect palindrome, except that spaces and punctuation are ignored in a standard palindrome. For example, “Madam, I’m Adam” is a standard palindrome because the characters are identical forward or backward, provided you remove the spaces and punctuation marks.
Write a PHP script that checks a word or a phrase (stored in a string variable) to determine if it is a standard palindrome, a perfect palindrome, or not a palindrome at all. Also, for each letter that the word/phrase contains, count and print the number of times that each consonant and vowel is encountered. Your output will look as follows:
Word/phrase: racecar
Perfect palindrome
Contains consonants:
r - 2
c - 2
Contains vowels:
a - 2
e - 1
Explanation / Answer
<?php
$word = "racecar"; // declare a varibale
$wordRem = preg_replace("/[^a-zA-Z]/", "", $word);//word after removing spacces and special characters
$reverse = strrev($word); // reverse the word
$vowels = array('a','e','i','o','u');//all vowels in array
if ($wordRem == $reverse){ // compare if the original word is same as the reverse of the same word
echo "Word/phrase: " . $word . "<br>";
echo "Perfect palindrome" . "<br>";
}
else{
echo "Word/phrase: " . $word . "<br>";
echo "Not a palindrome" . "<br>";
}
$wordVowel = "";
$wordConsonant = "";
$len = strlen($wordRem);
for($i=0; $i<$len; $i++){
if(in_array($wordRem[$i], $vowels))
{
$wordVowel .= $wordRem[$i];
}
else{
$wordConsonant .= $wordRem[$i];
}
}
echo "Contains consonants:" . "<br>";
foreach (count_chars($wordConsonant, 1) as $i => $val) {
echo chr($i) . "-" . $val . "<br>";
}
echo "Contains vowels:" . "<br>";
foreach (count_chars($wordVowel, 1) as $i => $val) {
echo chr($i) . "-" . $val . "<br>";
}
?>
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.