I got lots of result and codes about search string. But all are search single word. I want to search multiple word and any of word match string will be display.
Example:
$string = "Apple is a big tech company!";
$search = 'Apple Logo';
Now I want if "Apple Logo" or "Apple" or "Logo" in string then it will return True else it will show False.
How I do that? I already tried lot of PHP codes. I also see ElasticSearch
but I want something handy and easy to use.
if (stripos($string, $search) !== false) {
echo "Found";
}
答案 0 :(得分:4)
You can use an array of the words, replace them and check against the original:
if(str_ireplace(explode(' ', $search), '', $string) != $string) {
echo "Found";
}
Or loop the words and check as you would with a single word:
foreach(explode(' ', $search) as $word) {
if(stripos($string, $word) !== false) {
echo "Found";
break;
}
}
答案 1 :(得分:1)
我会使用preg_grep和其他一些奇特的东西。
$string = "Apple is a big tech company!";
$search = 'Apple Logo a';
$pattern = '/\b('.str_replace(' ', '|', preg_quote($search, '/')).')\b/i';
$arr = preg_grep($pattern, explode(' ', $string));
print_r($arr);
输出
Array ( [0] => Apple [2] => a )
在线测试
我把a
扔在那里只是为了炫耀。如您所见,它只匹配a
而非company
等。
作为奖励,它将正确地逃避搜索字符串中的任何正则表达式内容......
耶!
作为旁注,如果您愿意,也可以使用与preg_match_all相同的模式。
$string = "Apple is a big tech company!";
$search = 'Apple Logo a';
$pattern = '/\b('.str_replace(' ', '|', preg_quote($search, '/')).')\b/i';
$numMatch = preg_match_all($pattern,$string,$matches);
print_r($numMatch);
print_r($matches);
输出
2
Array (
[0] => Array (
[0] => Apple
[1] => a
)
[1] => Array (
[0] => Apple
[1] => a
)
)
测试
唯一真正的区别是你得到一个更复杂的数组(只需使用$matches[1]
)和匹配计数而不计算所说的数组。
答案 2 :(得分:-3)
you can use this STRPOS example:
$a = 'How are you?';
if (strpos($a, 'are') !== false) {
echo 'true';
}
this a little example.. good luck