dongle0396 2015-08-08 11:06
浏览 118
已采纳

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.

  • 写回答

1条回答 默认 最新

  • doudao0660 2015-08-08 11:13
    关注

    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
      
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程