开发者

Regex match that must contain all characters in a string

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 bas开发者_开发知识库ically 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  


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜