Palindrome checker


/ Published in: PHP
Save to your folder(s)

Script checks whether a given string is a palindrome


Copy this code and paste it in your HTML
  1. <?php
  2. // Declares variables I'll use later
  3. $forward_string = "";
  4. $backward_string = "";
  5.  
  6. // Function to compare two strings, takes a string for argument
  7. function strip_punctuation($string) {
  8. // Sets entire string to lower case
  9. $string = strtolower($string);
  10. // Uses regular expression to replace all non-word characters such as puncuation and whitespace with nothing
  11. $forward_string = preg_replace("/\W/", "", $string);
  12. // Reverses the above string and sets value to new variable
  13. $backward_string = strrev($forward_string);
  14.  
  15. // Conditional to compare the two strings. If they are equal, echo out "Palindrome", else if not, echo "Not a palindrome"
  16. if ( $forward_string == $backward_string ) {
  17. echo "Palindrome " . $forward_string;
  18. } else {
  19. echo "Not a palindrome " . $backward_string;
  20. }
  21.  
  22. }
  23. // Call the function
  24. strip_punctuation("Was it a car or a cat I saw?");
  25.  
  26. // Original code challenge at: https://www.reddit.com/r/dailyprogrammer/comments/3kx6oh/20150914_challenge_232_easy_palindromes/
  27. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.