Hello,
For my current project, I am trying to figure out how to check to see if a string typed into the text area is a palindrome. For this project, we are given most of the code, but I am supposed to fill in the code for the is_palindrome function that is given to me. I am not allowed to use the strrev function, recursion, or regular expressions and I am not allowed to change any other other code. I spent a few good hours trying to figure this out and after some research and trying to figure out it on my own, I got it to the point were it tells me if it is a palindrome or not, but I think the way I did it is recursion. I was never taught how to do recursion code, but after looking online what it is, I think my function has recursion. My questions for you guys are, is the code in the is_palindrome function recursion code, and if so, how could I put a loop (for or while) into that function that includes the strlen() and substr() function without making it recursion code?
Thanks so much.
<?php
//declare variables to store the string to be checked and the message to be displayed.
$string = $message = "";
//retrieve the string to be checked and then strip any invalid characters
if (filter_has_var(INPUT_GET, "string")) {
$string = trim(filter_input(INPUT_GET, 'string', FILTER_DEFAULT));
//remove all non-alphanumeric characters and then convert all characcters to lower cases
$string_stripped = strtolower(preg_replace("/[^A-Za-z0-9]/", "", $string));
}
if ($string != "") {
$result = is_palindrome($string_stripped);
if ($result)
$message = "\"" . $string . "\" is a palindrome.";
else
$message = "\"" . $string . "\" is NOT a palindrome.";
}
//this is the function that I am needed to fill out
function is_palindrome($str) {
if (strlen($str) == 0) {
return true;
}
if ($str[0] == $str[strlen($str) - 1]) {
return true and is_palindrome(substr($str, 1, strlen($str) - 2));
} else {
return false;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Checking Palindromes</title>
<link rel="stylesheet" href="styles.css" type="text/css" />
</head>
<body>
<h2>Checking Palindromes</h2>
<p>Enter a string and then click the <strong>Check</strong> button to see the result.</p>
<form action="palindrome.php" method="get" enctype="text/plain">
<table>
<tr>
<th>Enter a string: </th>
<td><input type="text" name="string" size="20" value="<?php echo $string ?>" required /></td>
</tr>
<tr>
<th>Result: </th>
<td><?php echo $message ?></td>
</tr>
</table>
<br>
<input type="submit" value="Check" />
</form>
</body>
</html>