Php 字符串中的多个单词搜索
Php multiple word search in a string
我得到了很多关于搜索字符串的结果和代码。但都是搜索单个词。我想搜索多个单词,将显示任何单词匹配字符串。
示例:
$string = "Apple is a big tech company!";
$search = 'Apple Logo';
Now I want if "Apple Logo" or "Apple" or "Logo" 在字符串中然后它会 return True 否则它会显示 False.
我该怎么做?我已经尝试了很多 PHP 代码。我也看到了 ElasticSearch
,但我想要一些方便易用的东西。
if (stripos($string, $search) !== false) {
echo "Found";
}
你可以使用这个STRPOS
示例:
$a = 'How are you?';
if (strpos($a, 'are') !== false) {
echo 'true';
}
这是一个小例子..祝你好运
您可以使用单词数组,替换它们并与原文进行核对:
if(str_ireplace(explode(' ', $search), '', $string) != $string) {
echo "Found";
}
或者循环单词并像检查单个单词一样进行检查:
foreach(explode(' ', $search) as $word) {
if(stripos($string, $word) !== false) {
echo "Found";
break;
}
}
我会使用 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]
)和匹配的计数而不计算所述数组。
我得到了很多关于搜索字符串的结果和代码。但都是搜索单个词。我想搜索多个单词,将显示任何单词匹配字符串。
示例:
$string = "Apple is a big tech company!";
$search = 'Apple Logo';
Now I want if "Apple Logo" or "Apple" or "Logo" 在字符串中然后它会 return True 否则它会显示 False.
我该怎么做?我已经尝试了很多 PHP 代码。我也看到了 ElasticSearch
,但我想要一些方便易用的东西。
if (stripos($string, $search) !== false) {
echo "Found";
}
你可以使用这个STRPOS 示例:
$a = 'How are you?';
if (strpos($a, 'are') !== false) {
echo 'true';
}
这是一个小例子..祝你好运
您可以使用单词数组,替换它们并与原文进行核对:
if(str_ireplace(explode(' ', $search), '', $string) != $string) {
echo "Found";
}
或者循环单词并像检查单个单词一样进行检查:
foreach(explode(' ', $search) as $word) {
if(stripos($string, $word) !== false) {
echo "Found";
break;
}
}
我会使用 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]
)和匹配的计数而不计算所述数组。