function getWordsWithOnlySpecifedLettersgetWordsWithOnlySpecifiedLetters(array $dictionary, string $letters)
{
foreach ($dictionary as $key => $value) {
if(mb_strlen($value) > mb_strlen($letters)) unset($dictionary[$key]);
}
$step = 0;
$strSplit = preg_split('//u', $letters, null, PREG_SPLIT_NO_EMPTY);
$result = [];
foreach ($dictionary as $word) {
$step++;
$wordSplit = preg_split('//u', $word, null, PREG_SPLIT_NO_EMPTY);
sort($wordSplit);
sort($strSplit);
if (array_map('mb_strtolower', $wordSplit) === array_map('mb_strtolower', $strSplit)) {
//echo "All specified letters from $letters are in $word | Step $step<hr>" . PHP_EOL;
$result[] = $word;
}
}
return $result;
}
$dictionary = ['apple', 'sample', 'api', 'pia', 'тоҷик'];
getWordsWithOnlySpecifedLettersgetWordsWithOnlySpecifiedLetters($dictionary, "aip");
getWordsWithOnlySpecifedLettersgetWordsWithOnlySpecifiedLetters($dictionary, "leamps");
function getWordsWithSpecifedLettersgetWordsWithSpecifiedLetters(array $dictionary, string $letters)
{
$step = 0;
mb_internal_encoding("UTF-8");
$result = [];
foreach ($dictionary as $word) {
$step++;
$wordSplit = preg_split('//u', $word, null, PREG_SPLIT_NO_EMPTY);
$strSplit = preg_split('//u', $letters, 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(array_diff($strSplit,$wordSplit)) === 0) {
//echo "$word contains all letters of $letters | Step $step<hr>" . PHP_EOL;
$result[] = $word;
}
}
return $result;
}
$dictionary = ['apple', 'sample', 'api', 'pia', 'тоҷик'];
getWordsWithSpecifedLettersgetWordsWithSpecifiedLetters($dictionary, "ple");