PHP正则表达式+通配符中的多个值

I just want to stress that I've been reading, trying and failing a lot before I asked this question. I can see similar questions but not exact duplicates.

I need to find a value that:

  • Could be in any case.
  • Could or could not end with something completely random E.g. "Cake is yummy"
  • May or may not be enclosed in /slashes/

This is what I'm currently doing:

  if ( $name == '/cake/' || $name == '/CAKE/' || $name == '/Cake/' || $name == '/CaKe/' || $name == 'CAKE' || $name == 'cake' { 

This is what I'm trying to do:

if(preg_match == (cake:) *(\([a-zA-Z]+\).+){

Can't quite get it to work.

You're basically searching for a case-insensitive Cake. Then just use the i flag.

  preg_match("~ Cake ~xi", $name)
                       ↑

If you also want to match for optional / slashes around, then add an altenative:

  preg_match("~ /Cake/  |  \b Cake \b ~xi", $name)
                ↑    ↑      ↑       ↑

Note the \b word boundary markers for the unenclosed cake, so you're not matching Cakeriky for example.

  1. If you want Cake to be at the start of the string, then it'll need an ^ marker.

     preg_match("~ ^  (/Cake/  |  \b Cake \b) ~xi", $name)
                   ↑
              start anchor
    
  2. If you additionally wanted to enforce some text thereafter being present (and not optional/ignored), then add another placeholder:

     preg_match("~ ^  (/Cake/  |  \b Cake \b)   .*\w.* ~xi", $name)
                                                   ↑
                                          at least one word char