Regular Expressions 101

Community Patterns

Palindromes

2

Regular Expression
PCRE2 (PHP >=7.3)

/
(?(DEFINE) (?<palindrome> # Recursive alternative first to match recursive palindromes. # Invert alternatives order to match nested palindromes individually # and (drastically) reduce backtracking. (?<l1>\p{L})\p{M}* [\s\p{P}]* (?&palindrome) [\s\p{P}]* \k<l1>\p{M}* | (?<l2>\p{L})\p{M}* [\s\p{P}]* \k<l2>\p{M}* | \p{L}\p{M}* ) ) (?<=[\s\p{P}]|^) (?&palindrome) (?(?=\s*\p{P}) (?:\s*\p{P})+ | (?=\s|$))
/
gix

Description

Matches palindromes:

  • arbitrary length
  • ignores non-significant characters (spaces, ponctuation)
  • ignores accents, provided the text is NFD-normalized
  • recursive palindromes (e.g. "a été à"): either match the longest one ("a été à") or the nested ones individually ("a", "été", "à") (see comment)
Submitted by NicolaF_ - a year ago (Last modified a year ago)