0

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");
1
  • 1
    How about iterating through the array using a foreach and validate on the values? Commented Nov 28, 2013 at 17:54

5 Answers 5

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this works very well indeed :) - @amal-murali
1

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

Comments

1

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

Comments

0

A function containing something like...

foreach ($arr as $value) {
  if (strpos($string, $value)) { return true;}
}
return false;

Comments

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.