Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to check if a string is a palindrome

Short answer

Compare the string with itself reversed:

<?php
 
var_dump('level' === strrev('level'));
var_dump('hello' === strrev('hello'));

Output:

bool(true)
bool(false)

A phrase with spaces and punctuation

Keep only letters and digits and lowercase them:

<?php
 
function isPalindrome(string $text): bool
{
    $clean = mb_strtolower(preg_replace('/[^\p{L}\p{N}]/u', '', $text));
    $chars = mb_str_split($clean);
 
    return $chars === array_reverse($chars);
}
 
var_dump(isPalindrome('A man, a plan, a canal: Panama'));
var_dump(isPalindrome('А роза упала на лапу Азора'));

Output:

bool(true)
bool(true)

Functions used in this recipe

  • strrev — Reverses a string.
  • mb_str_split — Splits a string into characters for any alphabet.
  • preg_replace — Replaces everything that matches a regular expression.

Thanks for reading!

Donate to the site — we work hard for you.