dongle0396 2015-08-08 03: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 03: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
      
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部