![](/img/trans.png)
[英]Filter array to retain all elements that have a key containing a searched string
[英]preg_grep outputting partial match
因此,我目前正在使用preg_grep查找包含字符串的行,但是如果一行包含特殊字符,例如“-。@”,我只需鍵入該行內的1個字母,它將作為匹配項輸出。
example@users.com
搜尋要求
ex
它會輸出
example@users.com
但如果搜索請求匹配“ example@users.com”,則僅應輸出“ example@users.com”,例如,僅在使用特殊字符的行上會出現此問題。
如果我在包含以下內容的行中搜索“ example”
example123
它會回應
not found
但是如果我搜索確切的字符串“ example123”
它當然也將按預期輸出
example123
所以問題似乎在於包含特殊字符的行。
我目前對grep的用法是
if(trim($query) == ''){
$file = (preg_grep("/(^\$query*$)/", $file));
}else{
$file = (preg_grep("/\b$query\b/i", $file));
$in = [
'example@users.com',
'example',
'example123',
'ex',
'ex123',
];
$q = 'ex';
$out = preg_grep("/^$q(?:.*[-.@]|$)/", $in);
print_r($out);
說明
^ : begining of line
$q : the query value
(?: : start non capture group
.* : 0 or more any character
[-.@] : a "special character", you could add all you want
| : OR
$ : end of line
) : end group
輸出:
Array
(
[0] => example@users.com
[3] => ex
)
編輯,根據評論:
您必須使用preg_replace
:
$in = [
'example@users.com',
'example',
'example123',
'ex',
'ex123',
];
$q = 'ex';
$out = preg_replace("/^($q).*$/", "$1", preg_grep("/^$q(?:.*[.@-]|$)/", $in));
print_r($out);
輸出:
Array
(
[0] => ex
[3] => ex
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.