简体   繁体   English

给定一个字符串和一个字符串数组,检查字符串是否包含数组中的所有单词

[英]Given a string, and an array of strings check if string contains all words in the array

So here is situation let's imagine a string and an array:所以这里的情况让我们想象一个字符串和一个数组:

$str = 'Sample string';
$arr = array('sample', 'string')

What would be the best way to determine if the given string has all of the words contained in the array?确定给定字符串是否包含数组中包含的所有单词的最佳方法是什么? String can be longer, and has additional words, it does not matter.字符串可以更长,并且有附加词,没关系。 The only thing I need, is a function that given a string and an array would return true, if string contains every single word that is in array (case and order I'm which they appear does not matter)我唯一需要的是一个函数,如果字符串包含数组中的每个单词(大小写和顺序无关紧要),则给定字符串和数组将返回 true

You can simply use str_word_count with extra parameter 1 like as您可以简单地将str_word_count与额外的参数1一起使用,例如

$str = 'Sample string';
$arr = array('sample', 'string');
$new_arr = array_intersect(array_map('strtolower',str_word_count($str,1)),$arr);
print_r($new_arr);

Output:输出:

Array
(
    [0] => sample
    [1] => string
)

Demo演示

Try this out.试试这个。

$strArray = explode(" ", $str);
$result = array_intersect($strArray, $arr);
if(sizeof($result) == sizeof($arr)){
   return TRUE;
}else{
   return FALSE;
}

if this don't work, then try swapping the inputs in array_intersect($arr, $strArray) You can add other functions to make all lowercase before comparing to give it a finishing touch.如果这不起作用,则尝试交换array_intersect($arr, $strArray)您可以添加其他函数以在比较之前将其全部小写,以进行最后的润色。

Try this one:试试这个:

<?php 
$words = array('sample', 'string');
$str = 'sample string';
strtolower($str);
$strArr = explode(' ',$str);
$wordfound = false;
foreach ($strArr as $k => $v) {
    if (in_array($v,$words)) {$wordfound = true; break;}
    foreach($words as $kb => $vb) {
        if (strstr($v, $kb)) $wordfound = true;
        break;
    }
}
if ($wordfound) {
    echo 'Found!';
}
else echo 'Not found!';

If performance matters, I would use an associative array:如果性能很重要,我会使用关联数组:

$words = array_flip(preg_split('/\\s+/', strtolower($str)));
$result = true;
foreach ($arr as $find) {
    if (!isset($words[$find])) {
        $result = false;
        break;
    }
}

Demo演示

$str = 'Sample string';
$str1=strtolower($str);


 $arr = array(
            'sample',
            'string'
        );

        foreach($arr as $val)
        {
            if(strpos($str1,strtolower($val)) !== false)
            {
                $msg='true';
            }
            else
            {
                $msg='false';
                break;
            }
        }

     echo $msg;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM