如何检查是否在字符串中找到(多个)单词然后
How to check if (multiple) words found in string then
public static function likecheck($str, $searchTerm) {
$searchTerm = strtolower($searchTerm);
$str = strtolower($str);
$pos = strpos($str, $searchTerm);
if ($pos === false)
return false;
else
return true;
}
它可以很好地匹配 $str
中的任何单个单词
$found = App\Helper::likecheck('Developers are very good','very');
if($found){
echo 'ok';
}
但我想通过提供更多用逗号分隔的单词来检查,如果找到任何单词则 return true
喜欢:
$found = App\Helper::likecheck('Developers are very good','very, good, gentle');
if($found){
echo 'found';
}
但它不会,因为它只能检查一个单词。
我建议您传递一个数组,而不是单个或逗号分隔的字符串。
以及推荐使用explode()
和array_intersect()
public static function likecheck($str, $searchTerm =array()) {
$explodedString = explode(' ', strtolower($str));
$searchTerm = array_map('strtolower', $searchTerm);
if(count(array_intersect($explodedString,$searchTerm)) > 0){
return true;
}else{
return false;
}
}
public static function likecheck($str, $searchTerm) {
$searchTerm = strtolower($searchTerm);
$str = strtolower($str);
$pos = strpos($str, $searchTerm);
if ($pos === false)
return false;
else
return true;
}
它可以很好地匹配 $str
中的任何单个单词$found = App\Helper::likecheck('Developers are very good','very');
if($found){
echo 'ok';
}
但我想通过提供更多用逗号分隔的单词来检查,如果找到任何单词则 return true
喜欢:
$found = App\Helper::likecheck('Developers are very good','very, good, gentle');
if($found){
echo 'found';
}
但它不会,因为它只能检查一个单词。
我建议您传递一个数组,而不是单个或逗号分隔的字符串。
以及推荐使用explode()
和array_intersect()
public static function likecheck($str, $searchTerm =array()) {
$explodedString = explode(' ', strtolower($str));
$searchTerm = array_map('strtolower', $searchTerm);
if(count(array_intersect($explodedString,$searchTerm)) > 0){
return true;
}else{
return false;
}
}