检查是否可以使用 PHP 从随机字符串创建单词

Check if a word can be created from a random letter string using PHP

<?php
    $randomstring = 'raabccdegep';
    $arraylist = array("car", "egg", "total");
?>

上面$randomstring是一个包含一些字母的字符串。 我有一个名为 $arraylist 的数组,其中包含 3 个单词,例如 'car' , 'egg' , 'total'.

现在我需要检查字符串 Using the words in array 并打印是否可以使用字符串创建单词。 例如,我需要一个输出 Like.

car is possible.
egg is not possible.
total is not possible.

另外请检查字母的重复。即,beep 也是可能的。因为字符串中包含两个e。但是egg是不行的,因为只有一个g.

这应该可以解决问题:

<?php
        $randomstring = 'raabccdegep';
        $arraylist = array("car", "egg", "total");

        foreach($arraylist as $word){
            $checkstring = $randomstring;
            $beMade = true;
            for( $i = 0; $i < strlen($word); $i++ ) {
                $char = substr( $word, $i, 1 );
                $pos = strpos($checkstring, $char);
                if($pos === false){
                    $beMade = false;
                } else {
                    substr_replace($checkstring, '', $i, 1);    
                }
            }
            if ($beMade){
                echo $word . " is possible \n";
            } else {
                echo $word . " is not possible \n";
            }
        }
    ?>
function find_in( $haystack, $item ) {
    $match = '';
    foreach( str_split( $item ) as $char ) {
        if ( strpos( $haystack, $char ) !== false ) {
            $haystack = substr_replace( $haystack, '', strpos( $haystack, $char ), 1 );
            $match .= $char;
        }
    }
    return $match === $item;
}

$randomstring = 'raabccdegep';
$arraylist = array( "beep", "car", "egg", "total");

foreach ( $arraylist as $item ) {
    echo find_in( $randomstring, $item ) ? " $item found in $randomstring." : " $item not found in $randomstring.";
}