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 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法