How does this PCRE pattern detect palindromes?
This question is an educational demonstration of the usage of lookahead, nested reference, and conditionals in a PCRE pattern to match ALL palindromes, including the ones that can't be matched by the recursive pattern given in the PCRE man page. Examine this PCRE pattern in PHP snippet: $palindrome = '/(?x) ^ (?: (.) (?= .* ( \1 (?(2) \2 | ) ) $ ) )* .? \2? $ /'; This pattern seems to detect palindromes, as seen in this test cases ( see also on ideone.com ): $tests = array( # palindromes '', 'a', 'aa', 'aaa', 'aba', 'aaaa', 'abba', 'aaaaa', 'abcba', 'ababa', # non-palindromes 'aab', 'abab',