dtfo55908 2016-02-07 09:20
浏览 102
已采纳

将REGEX与Sql语句一起使用

I'm wanting to check if in my column named "tag" it contains numbers with two digit numbers using Regex.

my query:

$FilterTag="3,2,11"
$sql = "SELECT * FROM table1 WHERE bTown = ? AND REGEXP_LIKE(tag, '.*[$FilterTag]')";

My table: db table tag

the only problem is that my query is finding single character numbers ,like instead of telling me that it contains 11 it will tell me that it contains 1.

Is there any way that i can group a character set of numbers?

  • 写回答

2条回答 默认 最新

  • duanqinbi9029 2016-02-07 09:29
    关注

    Your question was not clear!

    So you want to get entries with tag having 3 AND 2 AND 11.

    You'll have to split your string/filter 3,2,11, then generate the condition using a loop:

    $sql = "SELECT * FROM table1 WHERE bTown = ?";
    
    foreach (explode(",", $FilterTag) as $value)
        $sql .= " AND REGEXP_LIKE(tag, '\b$value\b')";
    

    which should produce the following query:

    SELECT * FROM table1 WHERE bTown = ? 
        AND REGEXP_LIKE(tag, '\b3\b')
        AND REGEXP_LIKE(tag, '\b2\b')
        AND REGEXP_LIKE(tag, '\b11\b')
    

    Extras:

    To allow only numbers from 1 to 99, use this regex:

    \b[1-9][0-9]?\b
    

    DEMO

    To allow two digits numbers (with leading zeros for numbers <10) use:

    \b(0[1-9]|[1-9][0-9])\b
    

    DEMO

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部