简体   繁体   中英

php regex - match from start and end of string

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?

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)\\/$/'

关于什么:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM