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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?