[英]FInd array of words in String using regex
我正在尋找字符串中的一些單詞,下面是我的代碼
$str="Chup Raho Episode 5 by Ary Digital 16th September 2014";
$keywords=array('Ary digital','geo');
echo in_string($keywords,$str,'all');
function in_string($words, $string, $option)
{
if ($option == "all") {
$isFound = true;
foreach ($words as $value) {
$isFound = $isFound && (stripos($string, $value) !== false); // returns boolean false if nothing is found, not 0
if (!$isFound) break; // if a word wasn't found, there is no need to continue
}
} else {
$isFound = false;
foreach ($words as $value) {
$isFound = $isFound || (stripos($string, $value) !== false);
if ($isFound) break; // if a word was found, there is no need to continue
}
}
return $isFound;
}
該函數返回true或false,如果找到的單詞返回1,否則返回0。我需要返回正在搜索的單詞,因為我想在mysql中對該單詞進行另一個搜索。 就像功能找到“ Ary digital”一樣,它應該返回“ ary digital found”。 需要幫助。謝謝。
您可能想做這樣的事情(未經測試):
preg_match('#(word1|word2|word3)#',$string,$matches);
然后,print_r($ matches)查看matchs數組的輸出並獲取您想要的位。 從那里您可以返回true / false等。
只需重寫您已有的內容即可。 而不是返回布爾值,而是將匹配的關鍵字推送到一個新數組,然后返回該數組。
function in_string($keywords, $string, $searchAll = true) {
$matches = array();
foreach ($keywords as $keyword) {
if (stripos($string, $keyword) !== false)
array_push($matches, $keyword);
if (!$searchAll)
break;
}
return $matches;
}
順便說一句,正則表達式比這慢得多(通常是10倍以上)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.