[英]preg_match all words in a string
尋找可能檢測$string
是否匹配$array
中的所有單詞。 預先未知的單詞順序(用戶輸入的文本)。
array(
'test',
'shmest',
'zest',
'fest',
'etcest'
);
我承諾我可以:
$is_match = true;
foreach ($array as $word) {
if (!strpos($string, $word) === false) {
$is_match = false;
break;
}
}
(可以|應該)我通過preg_match [_all]做出如上所述的事情嗎?
EDIT1
優先級是內存和快速工作。
測試了2個unswers並擁有https://eval.in/144266以上所以我的速度最快
$string
可以包含任何符號
您可以使用LookAheads創建RegEx:
$regex='/(?=.*?'.implode(')(?=.*?', $needles).')/s';
然后簡單檢查你的字符串:
if (preg_match($regex,$string)===1) echo 'true';
演示代碼: https : //eval.in/144296
RegEx解釋: http : //regex101.com/r/eQ0hU4
使用preg_split()
和array_intersect()
:
$words = preg_split("/(?<=\w)\b\s*/", $input, -1, PREG_SPLIT_NO_EMPTY);
echo (array_intersect($arr, $words) == $arr) ? 'True' : 'False';
基本上preg_split()
將輸入字符串拆分為單詞數組。 array_intersect()
檢查$arr
中的所有元素是否都出現在$words
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.