user874737
user874737

Reputation: 533

How to search strings within an array that has values containing two or more words (PHP)

I have an array which contains some elements with two words, for example array("Dark Blue", "Carnation Pink").. What function do I need to use to search an array value that contains a specified string to be search. If I searched "Dark", the value "Dark Blue" should show.

Upvotes: 3

Views: 97

Answers (2)

Micah Carrick
Micah Carrick

Reputation: 10197

Maybe a good old fashioned foreach loop?

$search_for = "Dark";

foreach (array("Dark Blue", "Carnation Pink") as $value) {
    if (strpos($value, $search_for) !== false) {
        echo "Found $value<br/>";
    }
}

Upvotes: 0

alex
alex

Reputation: 490243

You could use preg_grep().

$found = preg_grep('/\bDark\b/', $arr);

CodePad.

You could also use array_filter() and preg_match() with a regex..

$found = array_filter($arr, function($value) {
  return preg_match('/\bDark\b/', $value);
});

CodePad.

Upvotes: 1

Related Questions