views:

39

answers:

3

I'm sure this has already been asked and answered, but I honestly couldn't find my answer after searching for quite a bit and reading Regex Tutorial. What I'm looking to do is match a string that has the same characters and length as another string. For example, a string "abcde" would match "edcba" but would not match "abcdf" or "aabbc" or "abc".

Here is my test code with the closest I've come up with that uses a character class, but what I can't figure out is how to get regex to basically iterate through each character in the class once starting at the beginning of the match string:

$string = 'abcde';
$array  = array('edcba','eeeee','fghij','fedcba','qqq','cbaed','cba');
foreach ($array as $match)
{
    if (preg_match("/[$string]/i",$match))
        echo "TRUE  -> $match";
    else 
        echo "FALSE -> $match";
}

Which gives the result:

TRUE  -> edcba
TRUE  -> eeeee
FALSE -> fghij
TRUE  -> fedcba
FALSE -> qqq
TRUE  -> cbaed
TRUE  -> cba 

When what I really want is:

TRUE  -> edcba 
FALSE -> eeeee  
FALSE -> fghij  
FALSE -> fedcba 
FALSE -> qqq    
TRUE  -> cbaed  
FALSE -> cba  
A: 

I'm not sure you would want to use Regex in this. I think you'll want to use a plain old find statement for all your letters.

Keng
+6  A: 

Basically you are checking for anagrams. Why not sort the strings and compare for equality?

$string = 'abcde';
$string = str_sort($string);  // sort the string.
$array  = array('edcba','eeeee','fghij','fedcba','qqq','cbaed','cba');
foreach ($array as $match) {
        $match = str_sort($match);  // sort each match.
        if (strcmp($match,$string) == 0)  // now string compare.
                echo "TRUE  -> $match\n";
        else
                echo "FALSE -> $match\n";
}

function str_sort($string) {
// function to sort a string..not the best but works :) 
        $tmp = str_split($string);
        sort($tmp);
        return implode('',$tmp);
}

Code In Action

codaddict
DOH! Thanks makes way to much sense, I guess I got my mind stuck on regex and fell down the rabbit hole. Thanks.
DrPerdix
A: 

As an alternate to using a regex, you could convert each letter to a character then sort them and check the two strigns are equal.

Justin Wignall