Regular Expressions 101

Community Patterns

Community Library Entry

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_ - 2 years ago (Last modified 2 years ago)