0

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));
user3255841
  • 113
  • 1
  • 2
  • 8

1 Answers1

0
$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
)
Toto
  • 89,455
  • 62
  • 89
  • 125
  • still outputs everything containing " ex " i need exact match to be precise, so if q="ex" and line is " example " output should be nothing, if q="example" then output should be " example " – user3255841 Dec 29 '17 at 09:35
  • well if it contains @, ., - or other special chars.. the output shouldn't contain " example@users.com " due to q="ex" it should only output " ex " – user3255841 Dec 29 '17 at 09:40
  • @user3255841: I don't get your first comment, this is exactly what my script is doing, it outputs `ex` if line is `ex` ans nothing if line is `ex123` or `example`. For the oher comment, pleasde, edit your question and add test cases with extract of input file, some example of queries and expected result. – Toto Dec 29 '17 at 12:36
  • Okay your $q was " ex " and yourput was " ex " but also " example@users.com ", it shouldn't be outputting " example@users.com " because $q didn't = " example@users.com " – user3255841 Dec 29 '17 at 12:39