dongzhe3573 2011-11-26 12:21
浏览 236
已采纳

php regex - 从字符串的开头和结尾匹配

I used an online regex tester to build a simple regex, however using php's preg_match it's giving an unknown modifier for $.

Here is the regex:

if (preg_match('/(^Keyword1/$|^Keyword2/$)/', $input, $matches)) 

What I'm trying to do is check if $input equals either Keyword1/ or Keyword2/ (exact match). I know I can easily do this with "if ($input == 'Keyword1/')" however I'd rather have a few lines of regex vs a dozen if statements in the code.

Anyone help me out?

  • 写回答

3条回答

  • duanqiu3800 2011-11-26 12:23
    关注

    You need to escape the / inside the regex because / is also being used as delimiter:

    if (preg_match('/(^Keyword1\/$|^Keyword2\/$)/', $input, $matches)) 
                               ^            ^ 
    

    Alternatively use a different delimiter:

    if (preg_match('~(^Keyword1/$|^Keyword2/$)~', $input, $matches)) 
                    ^                         ^
    

    Since both your sub-regexs have common anchors you can simplify your regex as:

     if (preg_match('~^(Keyword1|Keyword2)/$~', $input, $matches)) 
    

    Why the warning in your regex ?

    '/(^Keyword1/$|^Keyword2/$)/'
    

    Since you are using / as delimiter, the 2nd / in your regex makes PHP think it is the end of your regex. Now PHP accepts regex modifiers like s, m, i after the closing delimiter. But in your case PHP sees a $ after the closing delimiter. Since $ is not a valid modifier you get the warning:

    PHP Warning: preg_match(): Unknown modifier '$' in ...

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

报告相同问题?

悬赏问题

  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳