Question

I have an array of say 4 strings. How do i check to see if ANY of them are in a string and then return a true value if ANY are found in the string.

Have tried strpos() but for that, the needle has to be a string or integer, and cannot be an array.

Is there a case-insensitive way other than checking each array item separately via a loop through the array?

Example text:

$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");
Was it helpful?

Solution

The best way would be to loop through the array of needles and check if it is found in the string:

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

Test:

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

Demo.

OTHER TIPS

Check this out:

$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!";
}

Running code: http://sandbox.onlinephpfunctions.com/code/79f47f7ca4d6b9d1617487ccccc11104f107ae66

Try this one:

$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);

A function containing something like...

foreach ($arr as $value) {
  if (strpos($string, $value)) { return true;}
}
return false;
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
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top