Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php Program to find Palindrome?

Tags:

php

Three steps to find the palindrome?

  1. use strrev on the given value

  2. Then split using the str_split.

  3. Then use foreach and concate the split value.

Example

$a = "madam";

$b =  strrev($a);

    $string_reverse = str_split($b);

    $palin = '';

    foreach($string_reverse as $value){

        $palin.= $value; 
    }

    print $palin;

    if($a == $palin){

        print "<br>Palindrome";

    } else {

        print "<br>Not Palindrome"; 

    }

Output

madam
Palindrome

like image 848
sudhakar Avatar asked Dec 06 '22 19:12

sudhakar


1 Answers

try this:

<?php
function check_plaindrome($string) {
    //remove all spaces
    $string = str_replace(' ', '', $string);

    //remove special characters
    $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string);

    //change case to lower
    $string = strtolower($string);

    //reverse the string
    $reverse = strrev($string);

    if ($string == $reverse) {
        echo "<p>It is Palindrome</p>";
    } 
    else {
        echo "</p>Not Palindrome</p>";
    }
}

$string = "A man, a plan, a canal, Panama";
check_plaindrome($string);


########Output#######
<p>It is Palindrome</p>
like image 95
FelixHo Avatar answered Dec 09 '22 16:12

FelixHo