HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Nicer way to check if string contains all words from an array

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
fromcheckallarraywordswaycontainsnicerstring

Problem

Currently I check whether a string contains all words from an array like this:

function contains($string, array $array) {
    $count = 0;
    foreach($array as $value) {
        if (false !== stripos($string,$value)) {
            ++$count;
        };
    }
    return $count == count($array);
}


Example call:

$string = 'Hello, people at Stackoverflow';
$array = array('Hello', 'People');

if (contains($string, $array)) {
    print 'This is true for the given example';
}


I wonder whether a more elegant, faster or even built-in way exists to improve this?

Solution

You could use something like this:

$string = 'Hello, people at Stackoverflow';
$array = array('Hello', 'People');
$i = count(array_intersect($array, explode(" ", preg_replace("/[^A-Za-z0-9' -]/", "", $string))));
echo ($i) ? "found ($i)" : "not found";


Outputs:


found (1)

(array_intersect is case sensitive)

Or if you'd like to make it a function, then you could do something like this:

function contains($needles, $haystack) {
    return count(array_intersect($needles, explode(" ", preg_replace("/[^A-Za-z0-9' -]/", "", $haystack))));
}

$string = 'Hello, people at Stackoverflow';
$array = array('Hello', 'People');
$i = contains($array, $string);
echo ($i) ? "found ($i)" : "not found";

Code Snippets

$string = 'Hello, people at Stackoverflow';
$array = array('Hello', 'People');
$i = count(array_intersect($array, explode(" ", preg_replace("/[^A-Za-z0-9' -]/", "", $string))));
echo ($i) ? "found ($i)" : "not found";
function contains($needles, $haystack) {
    return count(array_intersect($needles, explode(" ", preg_replace("/[^A-Za-z0-9' -]/", "", $haystack))));
}

$string = 'Hello, people at Stackoverflow';
$array = array('Hello', 'People');
$i = contains($array, $string);
echo ($i) ? "found ($i)" : "not found";

Context

StackExchange Code Review Q#63573, answer score: 6

Revisions (0)

No revisions yet.