Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP:Regex,必须包含列表中的所有字母_Php_Regex_Preg Match - Fatal编程技术网

PHP:Regex,必须包含列表中的所有字母

PHP:Regex,必须包含列表中的所有字母,php,regex,preg-match,Php,Regex,Preg Match,是否有人知道如何编写正则表达式模式,即: 假设我有像这样的数组中的字母 $letters = array('a','b','a'); 我们还有一个单词Alabama,我希望preg_match返回true,因为它包含两次字母a和B。但是单词Ab应该返回false,因为这个单词中没有两个a 有什么想法吗 编辑:我尝试的唯一模式是[a,b,a],但它在每个包含其中一个字母的单词上都返回true,并且不检查多个字母出现的情况您需要使用正则表达式吗?即使问题可以通过它们解决,代码也会非常复杂。 “手动

是否有人知道如何编写正则表达式模式,即:

假设我有像这样的数组中的字母

$letters = array('a','b','a');
我们还有一个单词Alabama,我希望preg_match返回true,因为它包含两次字母a和B。但是单词Ab应该返回false,因为这个单词中没有两个a

有什么想法吗


编辑:我尝试的唯一模式是[a,b,a],但它在每个包含其中一个字母的单词上都返回true,并且不检查多个字母出现的情况

您需要使用正则表达式吗?即使问题可以通过它们解决,代码也会非常复杂。 “手动”解决方案将更加清晰,并且需要线性时间:

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;
}
函数stringContainsAllCharacters(字符串$str,数组$chars):bool
{
$actualCharCounts=array_count_value(str_split($str));
$requiredCharCounts=数组计数值($chars);
foreach($requiredCharCounts为$char=>$count){
如果(!array_key_存在($char,$actualCharCounts)|$$actualCharCounts[$char]<$count){
返回false;
}
}
返回true;
}

我认为您不必使流程过于复杂。您可以遍历
字母
并检查
单词
中是否存在,如果所有字母都存在,则返回
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)


请注意,这是不区分大小写的,如果您需要它,请将
stripos
替换为
strpos

数组内容的顺序是否与字符串中出现的顺序相同?@nu11p01n73R no。。它们只需要在字符串中的某个位置具有相同或更高的发生次数。请您进一步澄清我的问题好吗?
我们有一个单词Alabama是什么意思?
试试
^aba\z/gm
如果aba被修复,它会工作的。@ChoncholMahmud将给应用程序一个字母数组,它应该查找包含它们的单词。。。因此,如果我传递申请信(a,b,a),它应该返回单词Alabama,因为它包含两个或多个字母a和一个或多个字母b。但它不会返回单词Ab,因为它不包含两个字母a