So I'm currently using preg_grep to find lines containing string, but if a line contains special chars such as " - . @ " I can simply type 1 letter that is within that line and it will output as a match.. example of line
example@users.com
search request
ex
and it will output
example@users.com
but it should only output " example@users.com " if search request matches " example@users.com " this problem only occurs on lines using special chars, for example
if i search " example " on a line that contains
example123
it will respond
not found
but if i search the exact string " example123 "
it will of course output as it suppose too
example123
so the issue seems to lay with lines containing special characters..
my current usage of grep is,
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);
Explanation
^ : 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
Output:
Array
(
[0] => example@users.com
[3] => ex
)
Edit, according to comment:
You have to use preg_replace
:
$in = [
'example@users.com',
'example',
'example123',
'ex',
'ex123',
];
$q = 'ex';
$out = preg_replace("/^($q).*$/", "$1", preg_grep("/^$q(?:.*[.@-]|$)/", $in));
print_r($out);
Ooutput:
Array
(
[0] => ex
[3] => ex
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.