Skip to content

Instantly share code, notes, and snippets.

@voidnerd
Last active July 8, 2017 13:30
Show Gist options
  • Save voidnerd/b91299149817da61928c4756a7169f30 to your computer and use it in GitHub Desktop.
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).
<?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