2017-05-25 140 views
0
<?php 
    $randomstring = 'raabccdegep'; 
    $arraylist = array("car", "egg", "total"); 
?> 

以上$randomstring是一个包含一些字母的字符串。 而我有一个名为$arraylist的数组,其中包含3个字,如'car' , 'egg' , 'total'检查是否可以使用PHP随机字母串创建一个单词

现在我需要检查字符串使用数组中的单词并打印,如果可以使用字符串创建单词。例如,我需要一个Output Like。

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

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

+0

是否一旦它的验证字符串中使用的字符落下?例如我们搜索汽车和验证字符串是“thecar”(汽车发现然后验证字符串现在) - >“the”? –

+0

号可以重复使用。 – AdhershMNair

回答

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

完美。谢谢。最后3行应该在$ arraylist的foreach循环中。 – AdhershMNair

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"; 
    } 
} 
?> 
+0

当我试过这个。我有'鸡蛋可能'。但根据我的需要,“蛋”这个词应该是可能的。 – AdhershMNair

相关问题