How to check whether the letters of a word exist in a string (order doesn't matter) in PHP

1 Answer

0 votes
/**
 * Determines whether all letters in the specified word can be
 * formed from the letters available in the sentence.
 *
 * Rules:
 * - Letter order does not matter.
 * - Comparison is case-insensitive.
 * - Non-alphabetic characters are ignored.
 *
 * @param string $sentence Source text containing available letters.
 * @param string $word     Word to check.
 *
 * @return bool True if the word can be formed; otherwise false.
 */
function containsWordLetters(string $sentence, string $word): bool
{
    $available = array_fill(0, 26, 0);

    // Count available letters in the sentence.
    foreach (str_split(strtolower($sentence)) as $char) {
        if ($char >= 'a' && $char <= 'z') {
            $available[ord($char) - ord('a')]++;
        }
    }

    // Consume letters required by the word.
    foreach (str_split(strtolower($word)) as $char) {
        if ($char < 'a' || $char > 'z') {
            continue;
        }

        $index = ord($char) - ord('a');

        if (--$available[$index] < 0) {
            return false;
        }
    }

    return true;
}

// Example usage.
$sentence = 'Bright stars shine above calm valleys at night.';
$word = 'satellite';

var_dump(containsWordLetters($sentence, $word));

$word = 'satellllite'; // Requires 5 occurrences of 'l'

var_dump(containsWordLetters($sentence, $word));



/*
run:

bool(true)
bool(false)

*/

 



answered Sep 26 by avibootz

Related questions

...