views:

56

answers:

4

How can you match the following words by PHP, either by regex/globbing/...?

Examples

INNO, heppeh, isi, pekkep, dadad, mum

My attempt would be to make a regex which has 3 parts:

  1. 1st match match [a-zA-Z]*
  2. [a-zA-Z]?
  3. rotation of the 1st match // Problem here!

The part 3 is the problem, since I do not know how to rotate the match. This suggests me that regex is not the best solution here, since it is too very inefficient for long words.

+3  A: 

Regexs are not suitable for finding palindromes of an arbitrary length.

However, if you are trying to find all of the palindromes in a large set of text, you could use regex to find a list of things that might be palindromes, and then filter that list to find the words that actually are palindromes.

For example, you can use a regex to find all words such that the first X characters are the reverse of the last X characters (from some small fixed value of X, like 2 or 3), and then run a secondary filter against all the matches to see if the whole word is in fact a palindrome.

Daniel LeCheminant
+4  A: 

I think regex are a bad solution. I'd do something with the condition like: ($word == strrev($word)).

Marko
+1  A: 

In PHP once you get the string you want to check (by regex or split or whatever) you can just:

if ($string == strrev($string)) // it's a palindrome!
beggs
A: 

i think this regexp can work

  $re = '~([a-z])(.?|(?R))\1~';
stereofrog
Doesn't seem to work for me: php -r 'var_dump(preg_match("~([a-z])(.?|(?R))\1~", "racecar"));'
Frank Farmer
use single ' quotes around regexp, not double "
stereofrog