PHP - 检查数组的所有元素是否都在字符串中

标签 php arrays string

我有一个数组 $my_array,包含 n 元素和一个字符串 $my_string。我想检查 $my_array 的所有元素是否都在 $my_string 中。只要它们都在那里,它们在字符串中的顺序并不重要。我正在寻找最有效的解决方案,仅当所有元素都存在时才能获得 TRUE

正确:

$my_array = array("big", "blue", "sky", "dog"); 
$my_string = "my big dog loves the blue sky"; 

错误:

$my_array = array("big", "blue", "sky", "dog"); 
$my_string = "the big blue sky"; 

最佳答案

给你,不要害怕数组。

  $my_array = array("big", "blue", "sky", "dog");
  $my_string = "my big dog loves the blue sky"

  function arrayInString( array $my_array, $my_string ){
    $my_string = explode(' ', $my_string);
    // difference return all elements of array one not in array two
    $diff = array_diff($my_array, $my_string);
    if(empty( $diff )){
        //if there is no difference there are no elements not in the string.
        return true;
    }
    return false;
 }

没有循环的乐趣!

如果有标点符号可以用

preg_split('/^\w/', $my_string );

而不是爆炸

关于PHP - 检查数组的所有元素是否都在字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27726189/

相关文章:

PHP多重循环生成新数组

java - 在 Java 中解析制表符分隔文本文件时出现错误 ArrayIndexOutOfBoundsException

java - string.replaceAll 替换出现的地方

php - 在 EasyPost 中定义运输方式或费率

php - Symfony2 在数据库驱动程序上给出了 ParameterNotFoundException

php - 如何在sql数据库中搜索多个字段和多个值

arrays - 在 Swift 中添加两个数组的元素而不附加在一起

c - 在C中合并两个不同大小的字符串

c - C 中的字符串比较问题

php - 按城市定义自定义订单