![](/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.