preg_grep outputting partial match

426 views Asked by At

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

[email protected]

search request

ex

and it will output

[email protected]

but it should only output " [email protected] " if search request matches " [email protected] " 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));
1

There are 1 answers

4
Toto On
$in = [
    '[email protected]',
    '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] => [email protected]
    [3] => ex
)

Edit, according to comment:

You have to use preg_replace:

$in = [
    '[email protected]',
    'example',
    'example123',
    'ex',
    'ex123',
];
$q = 'ex';
$out = preg_replace("/^($q).*$/", "$1", preg_grep("/^$q(?:.*[.@-]|$)/", $in));
print_r($out);

Ooutput:

Array
(
    [0] => ex
    [3] => ex
)