2
votes

Does anyone know how to write regex pattern, that does this:

let's say I have letters in array like

$letters = array('a','b','a');

and also we have a word Alabama and I want preg_match to return true, since it contains letter A two times and B. But it should return false on word Ab, because there aren't two A in that word.

Any ideas ?

EDIT: the only pattern I tried was [a,b,a] but it returns true on every word that does contain one of these letters and also doesn't check it for multiple letter occurences

2
Will the contents of the array will be in the same order as they occur in the string? - nu11p01n73R
@nu11p01n73R no .. they only have to be somewhere in the string with same or higher number of occurences - Bezdutchek
could you clear me more? what do you mean by we have a word Alabama? try with ^aba\z/gm if aba is fixed it will work. - Chonchol Mahmud
@ChoncholMahmud Ill give an application an array of letters and it should look for words that contain them ... so if I pass application letters (a,b,a), it should return word Alabama, as it contains two or more letters A and one or more letter B. But it wont return word Ab, sice it doesnt contain two letters A - Bezdutchek

2 Answers

1
votes

I think you don't have to overcomplicate the process. You can traverse the letters and check if the exists in the word, if all the letter are there, return true. Something like this:

$letters = array('a','b','a');
$word = "Alabama";

function inWord($l,$w){
    //For each letter
    foreach($l as $letter){ 
        //check if the letter is in the word
        if(($p = stripos($w,$letter)) === FALSE) 
            //if false, return false
            return FALSE;
        else
            //if the letter is there, remove it and move to the next one
            $w = substr_replace($w,'',$p,1);
    }
    //If it found all the letters, return true
    return TRUE;
}

And use it like this: inWord($letters,$word);

Please note this is case insensitive, if you need it case sensitive replace stripos by strpos

0
votes

Must you need to use regular expressions? Even if the problem can be solved through them, the code will be very complicated. "Manual" solution will be clearer and takes linear time:

function stringContainsAllCharacters(string $str, array $chars): bool 
{
    $actualCharCounts   = array_count_values(str_split($str));
    $requiredCharCounts = array_count_values($chars);
    foreach ($requiredCharCounts as $char => $count) {
        if (!array_key_exists($char, $actualCharCounts) || $actualCharCounts[$char] < $count) {
            return false;
        }
    }
    return true;
}