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 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi