2016-11-21 68 views
2

所有字母有谁知道怎么写正则表达式,这是否:PHP:正则表达式,必须包含列表

比方说,我在阵列信件像

$letters = array('a','b','a'); 

而且我们有一个单词阿拉巴马州,我希望preg_match返回true,因为它包含字母A两次和B。但它应该在单词Ab上返回false,因为该单词中没有两个A.

任何想法?

编辑:我想是[A,B,A],但它返回的每一个确实包含这些字母之一,也是真正的字不检查它的多个信OCCURENCES

+2

更换stripos将数组的内容将是按照它们在字符串中出现的顺序排列? – nu11p01n73R

+0

@ nu11p01n73R no ..他们只需要在字符串中的某处出现相同或更多的出现次数 – VespaQQ

+0

您能否清除我更多? “我们有一个词阿拉巴马州?”如果aba是固定的,它将起作用,你用什么意思?'aba \ z/gm'。 –

回答

0

必须唯一模式需要使用正则表达式?即使问题可以通过他们解决,代码将会非常复杂。 “手册”的解决方案会更清楚,并采取线性时间:

function stringContainsAllCharacters(string $str, array $chars): bool 
{ 
    $actualCharCounts = array_count_values(str_split($str)); 
    $requiredCharCounts = array_count_values($chars); 
    foreach ($requiredCharCounts as $char => $count) { 
     if (!array_key_exists($char, $actualCharCounts) || $actualCharCounts[$char] < $count) { 
      return false; 
     } 
    } 
    return true; 
} 
1

我觉得你不必过于复杂的过程。您可以遍历letters并检查word中是否存在,如果所有字母都在那里,则返回true。事情是这样的:

$letters = array('a','b','a'); 
$word = "Alabama"; 

function inWord($l,$w){ 
    //For each letter 
    foreach($l as $letter){ 
     //check if the letter is in the word 
     if(($p = stripos($w,$letter)) === FALSE) 
      //if false, return false 
      return FALSE; 
     else 
      //if the letter is there, remove it and move to the next one 
      $w = substr_replace($w,'',$p,1); 
    } 
    //If it found all the letters, return true 
    return TRUE; 
} 

而且使用这样的:inWord($letters,$word);

请注意,这是不区分大小写的,如果你需要它区分大小写的strpos