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

时间:2017-05-25 09:48:47

标签: php arrays string word letter

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

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

现在我需要检查字符串使用数组中的单词并打印是否可以使用字符串创建单词。 例如,我需要一个类似输出。

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

另请检查重复的信件。也就是说,beep也是可能的。因为该字符串包含两个e。但egg是不可能的,因为只有一个g

2 个答案:

答案 0 :(得分:3)

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.";
}

答案 1 :(得分:0)

This should do the trick:
<?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";
    }
}
?>
相关问题