Search code examples
phpregexpreg-grep

How to find words with only/more specified letters using preg_grep in array?


I have sample function for searching words from array with specified letters:

public static function getWords($words, $specifed_letters) 
{ 
    $pattern = is_array($specifed_letters) ? '/[' . implode("", 
    $specifed_letters) . ']/u' : '/[' .$specifed_letters. ']/u';
    $result = preg_grep($pattern, $array_words);
    return $result;
}

Example usage:

$words = ["apple", "sample", "app", "тоҷик", "отабек", "баҳодурбек"];
$result = getWords($words, $letters = ['l', 's']);

This example will return words: apple, sample. Because in this words have letters "l" or "s".

How I can search words where have all specifed letters in word?

For example if I add to specifed letters "app" then from words array must be return words: app, apple.

And how search word with only specifed letters. For example I will write word "app" in shuffled variant "pap". And how I can get on result only word "app" without "apple"?


Solution

  • You could split the word characters to an array and loop them, and split the characters from the specified string to an array.

    If one of the word characters occur in the characters from the specified string array, remove the character from both arrays.

    Once the loop is done, verify that there are no more characters left in the characters from the specified string array.

    $words = ["apple", "sample", "app", "justappgg", "тоҷик", "отабек", "баҳодурбек", "APELCIN", "API", "pap"];
    mb_internal_encoding("UTF-8");
    
    foreach ($words as $word) {
        $wordSplit = preg_split('//u', $word, null, PREG_SPLIT_NO_EMPTY);
        $strSplit = preg_split('//u', $str, null, PREG_SPLIT_NO_EMPTY);
        $wordSplit = array_filter($wordSplit, function ($x) use (&$strSplit) {
            if (in_array(strtolower($x), array_map('strtolower', $strSplit), true)) {
                $pos = array_search(strtolower($x), array_map('strtolower', $strSplit), true);
                unset($strSplit[$pos]);
                return false;
            }
            return true;
        });
        if (count($strSplit) === 0) {
            echo "$word contains all letters of $str" . PHP_EOL;
        }
    }
    

    Demo