开发者

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.


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.


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/>";
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜