Split each word into an array containing all the individual letters. (Can be done for example using preg_split('//u', 'word', -1, PREG_SPLIT_NO_EMPTY)
)
For each word, count how many times each letter occurs - array_count_values
gives you an array with the input array values (our individual letters) as keys, and the count as value.
Loop over the counted letters from the second word, and check if the count of the same letter in the first word is greater or equal at least. If that is not the case for any of the letters from the second word, it is not “contained” in the first one.
Let’s wrap all that into a nice little function, and we get the following:
function does_a_contain_b($a, $b) {
// split both words into individual letters, and count their occurrences
$letters_given = array_count_values(preg_split('//u', $a, -1, PREG_SPLIT_NO_EMPTY));
$letters_needed = array_count_values(preg_split('//u', $b, -1, PREG_SPLIT_NO_EMPTY));
// we assume b is going to be contained in a for now
$contained = true;
foreach($letters_needed as $letter => $count) {
// if the letter from 2nd word does not occur in the 1st one at all,
// or the count in 2nd is not at least equal to that of 1st,
// we set our flag to false, and break out of the loop
if(!isset($letters_given[$letter]) || $letters_given[$letter] < $count) {
$contained = false;
break;
}
}
return $contained;
}
// a couple of test cases
var_dump(
does_a_contain_b('ahwerlyp', 'help'), // true
does_a_contain_b('ahwerlyp', 'hhelp'), // false
does_a_contain_b('ahwerlyp', 'hype'), // true
does_a_contain_b('ahwerlyp', 'foobar') // false
);