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

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?

我使用在线正则表达式测试程序来构建一个简单的正则表达式,但是使用php的preg_match它为$提供了一个未知的修饰符。 p>

这是正则表达式: p>

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

我要做的是检查$ input是否等于Keyword1 /或Keyword2 /(完全匹配)。 我知道我可以使用“if($ input =='Keyword1 /')轻松完成此操作”但是我宁愿在代码中使用几行正则表达式和十几个if语句。 p> 有人帮帮我吗? p> div>

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 ...

The issue is that you've used the / inside your regex without escaping it.

Here's what you're looking for, but maybe a little better:

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

What about:

preg_match('/^Keyword[1-2]\/$/', $input, $matches)