查找单词是否存在于数组或字符串中 PHP
Find if word exist in array or string PHP
我正在尝试查找数组中的任何字符串是否存在于单词数组中。
例如:
$key = ["sun","clouds"];
$results = ["Sun is hot","Too many clouds"];
如果 $key
中的任何一个存在于 $results
到 return true
使用下面的脚本我得到了我想要的结果,但前提是 $results
中的单词与 $key
中的单词完全相同。
function contain($key = [], $results){
$record_found = false;
if(is_array($results)){
// Loop through array
foreach ($results as $result) {
$found = preg_match_all("/\b(?:" .join($key, '|'). ")\b/i", $result, $matches);
if ($found) {
$record_found = true;
}
}
} else {
// Scan string to find word
$found = preg_match_all("/\b(?:" .join($key, '|'). ")\b/i", $results, $matches);
if ($found) {
$record_found = true;
}
}
return $record_found;
}
如果 $results
中的单词是 Enjoy all year round **sunshine**
我的函数 returns false
因为找不到单词 sun。如果字符串包含该字符串作为单词的一部分,我如何将函数更改为 return true?
我希望单词 sun
与 sun
或 sunshine
相匹配。
TIA
如前所述,您可以从 here 领取支票
而不是正则表达式使用它 + mb_strtolower 在循环中:
<?php
$keys = ["sun","clouds"];
$results = ["Sun is hot","Too many clouds"];
foreach ($keys as $key) {
foreach ($results as $result) {
if (strpos(mb_strtolower($result), mb_strtolower($key)) !== false) {
return true;
}
}
}
return false;
我正在尝试查找数组中的任何字符串是否存在于单词数组中。
例如:
$key = ["sun","clouds"];
$results = ["Sun is hot","Too many clouds"];
如果 $key
中的任何一个存在于 $results
到 return true
使用下面的脚本我得到了我想要的结果,但前提是 $results
中的单词与 $key
中的单词完全相同。
function contain($key = [], $results){
$record_found = false;
if(is_array($results)){
// Loop through array
foreach ($results as $result) {
$found = preg_match_all("/\b(?:" .join($key, '|'). ")\b/i", $result, $matches);
if ($found) {
$record_found = true;
}
}
} else {
// Scan string to find word
$found = preg_match_all("/\b(?:" .join($key, '|'). ")\b/i", $results, $matches);
if ($found) {
$record_found = true;
}
}
return $record_found;
}
如果 $results
中的单词是 Enjoy all year round **sunshine**
我的函数 returns false
因为找不到单词 sun。如果字符串包含该字符串作为单词的一部分,我如何将函数更改为 return true?
我希望单词 sun
与 sun
或 sunshine
相匹配。
TIA
如前所述,您可以从 here 领取支票 而不是正则表达式使用它 + mb_strtolower 在循环中:
<?php
$keys = ["sun","clouds"];
$results = ["Sun is hot","Too many clouds"];
foreach ($keys as $key) {
foreach ($results as $result) {
if (strpos(mb_strtolower($result), mb_strtolower($key)) !== false) {
return true;
}
}
}
return false;