duanjiyun7391 2010-07-14 12:49
浏览 15
已采纳

我的preg_match语法有效吗?

I'm adding an if statement to my database abstraction layer to pick out any attempted queries to a handful of database tables.

Basically, if my application attempts to create, read or destroy data from a database table called either members or members_profiles I want to invoke my if statement.

if (
    preg_match('/INSERT INTO [members|members_profiles]/', $sql) ||
    preg_match('/UPDATE [members|members_profiles]/', $sql) ||
    preg_match('/DELETE FROM [members|members_profiles]/', $sql))
{
    // do if statement stuff here...
}

I'm no regular expression/preg-match master, but will the above if statement return true if a SQL query matches:

  • INSERT INTO members ... or INSERT INTO members_profiles ...
  • UPDATE members ... or UPDATE members_profiles ...
  • DELETE FROM members ... or DELETE FROM members_profiles ...

Or is my preg-match syntax way off?

  • 写回答

5条回答 默认 最新

  • donglv1831 2010-07-14 12:53
    关注

    Just one regex will be enough:

    if (preg_match('/(?i)(INSERT\s+INTO|UPDATE|DELETE\s+FROM)(?-i)\s+(members|members_profiles)/', $sql))
    {
        // do if statement stuff here...
    }
    

    note the () instead of [] and \s+ instead of spaces. because SQL is valid with any number of nay whitespace, and \s+ matches them all. The + behind \s means that it must be at least one whitespace, but it can be more. The (?i) means that all following characters will be checked case insensitive, and the (?-i) turn case sensitivity on again. Since SQL commands are case insensitive.

    (abc|def) matches abc or def
    [abc|def] matches a, b, c, |, d, e or f

    To try out a regular expression you can use http://rubular.com/, it says it's written in ruby for testing regex in ruby, but valid regex should be independent of language, so it can be used to test common regular expressions, that work in other languages, too.

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

报告相同问题?

悬赏问题

  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表