【问题标题】:preg_grep outputting partial matchpreg_grep 输出部分匹配
【发布时间】:2017-12-29 08:47:37
【问题描述】:

所以我目前使用 preg_grep 来查找包含字符串的行,但是如果一行包含特殊字符,例如“-.@”,我可以简单地键入该行中的 1 个字母,它将作为匹配输出。线条示例

example@users.com

搜索请求

ex

它会输出

example@users.com

但是如果搜索请求匹配“example@users.com”,它应该只输出“example@users.com”这个问题只发生在使用特殊字符的行上,例如

如果我在包含

的行上搜索“示例”
example123

它会响应

not found

但如果我搜索确切的字符串“example123”

它当然也会像它假设的那样输出

example123

所以问题似乎在于包含特殊字符的行..

我目前对 grep 的使用是,

    if(trim($query) == ''){
        $file = (preg_grep("/(^\$query*$)/", $file));
    }else{
        $file = (preg_grep("/\b$query\b/i", $file));

【问题讨论】:

    标签: php preg-grep


    【解决方案1】:
    $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
    )
    

    【讨论】:

    • 仍然输出包含“ ex ”的所有内容,我需要精确匹配才能精确,所以如果 q="ex" 和 line 是 "example" 输出应该什么都没有,如果 q="example" 那么输出应该成为“榜样”
    • 如果它包含@、.、- 或其他特殊字符.. 输出不应包含“example@users.com”,因为 q="ex" 它应该只输出“ex”
    • @user3255841:我没有得到您的第一条评论,这正是我的脚本正在做的事情,如果 line 是 ex,它会输出 ex 如果 line 是 ex123 或 @ 则没有任何内容987654330@。对于其他评论,请编辑您的问题并添加带有输入文件提取的测试用例、一些查询示例和预期结果。
    • 好吧,你的 $q 是“ex”,你的输入是“ex”,但也是“example@users.com”,它不应该输出“example@users.com”,因为 $q 没有t = "example@users.com"
    猜你喜欢
    • 1970-01-01
    • 2011-09-19
    • 2021-05-07
    • 1970-01-01
    • 1970-01-01
    • 2014-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多