Last active
July 8, 2017 13:30
-
-
Save voidnerd/b91299149817da61928c4756a7169f30 to your computer and use it in GitHub Desktop.
A php function that checks if string is Palindrome using OOP (Palindrome is a string that reads the same left-to-right and right-left-to-left).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Palindrome { | |
public $words; | |
public $regex = '/[^A-Za-z0–9]/'; | |
public $reserved; | |
public function __construct( $words) | |
{ | |
$this->words = $words; | |
} | |
public function checkPalindrome() | |
{ | |
//remove all spaces if any | |
$this->words = str_replace(' ', '', $this->words); | |
//remove unwanted characters including numbers | |
$this->words = preg_replace($this->regex, '', $this->words); | |
//convert word to lower case | |
$this->words = strtolower($this->words); | |
//reverse the word for comparison | |
$this->reversed = strrev($this->words); | |
//compare word(s) and reserved word(s) | |
if($this->words == $this->reversed){ | |
return true; | |
} else { | |
return false; | |
} | |
} | |
} | |
//instantiate object | |
$word = new Palindrome('aadaa'); | |
//call function | |
$words->checkPalindrome(); //Output: True | |
//instantiate object | |
$word2 = new Palindrome('another'); | |
//call function | |
$word2->checkPalindrome(); //Output: False | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment