PHP检查任何数组项的字符串

时间:2013-11-28 17:53:07

标签: php arrays string strpos

我有一个说4个字符串的数组。我如何检查它们中的任何一个是否在字符串中,然后如果在字符串中找到ANY则返回一个真值。

已尝试过strpos(),但为此,针必须是字符串或整数,并且不能是数组。

除了通过数组循环单独检查每个数组项之外,是否存在不区分大小写的方法?

示例文字:

$string = "A rural position on a working dairy farm but within driving distance 
of the sea and local villages, also sharing an indoor pool";

$arr = array("farm", "Working farm", "swimming pool", "sea views");

5 个答案:

答案 0 :(得分:2)

最好的方法是遍历针阵列并检查它是否在字符串中找到:

function stripos_a($arr, $string) {
    foreach ($arr as $search) {
        if (stripos($string, $search) !== false) return true;
    }
    return false;
}

测试:

var_dump(stripos_a($arr, $string)); // bool(true)

Demo.

答案 1 :(得分:1)

检查出来:

$string = "A rural position on a working dairy farm but within driving distance of the sea and local villages, also sharing an indoor pool";
$arr = array("farm", "Working farm", "swimming pool", "sea views");

$exploded = explode(' ', $string);
foreach ($arr as $query) {
  if (in_array($query, $exploded))
    echo "<br/>{$query} founded!";
}

正在运行代码:http://sandbox.onlinephpfunctions.com/code/79f47f7ca4d6b9d1617487ccccc11104f107ae66

答案 2 :(得分:1)

试试这个:

$string = "A rural position on a working dairy farm but within driving distance of the sea and local villages, also sharing an indoor pool";
$arr = array("farm", "Working farm", "swimming pool", "sea views");

$match = (bool) preg_match("/(".join("|", $arr).")/i", $string);

var_dump($match);

答案 3 :(得分:0)

包含类似......

之类的函数
foreach ($arr as $value) {
  if (strpos($string, $value)) { return true;}
}
return false;

答案 4 :(得分:0)

function searchWords($string,$words)
{
    foreach($words as $word)
    {
        if(stristr($string," " . $word . " ")) //spaces either side to force a word
        {
            return true;
        }
    }
    return false;
}

<强> USAGE

$string = 'A rural position on a working dairy farm but within driving distance of the sea and local villages, also sharing an indoor pool';
$searchWords = array("farm", "Working farm", "swimming pool", "sea views");

if(searchWords($string,$searchWords))
{
     //matches
}