dongtun3328 2014-11-08 10:05
浏览 50
已采纳

PHP preg_match - 匹配一个完全独立的关键字?

How can I match a keyword that is completely on its own?

For instance I only want to match hello in a string like these,

/say/hello/world/
/say/hello/

but not in these,

/say/helloworld/
/say/hello-world/
/say/hello+world/
/say_hello_world/

So far with this pattern,

var_dump(preg_match('~.*?(?=hello)~i', $string)); // int 1

It matches all of them!

I only want /something/hello/world/ to be int 1 - is it possible?

  • 写回答

2条回答 默认 最新

  • doumisha5081 2014-11-08 10:07
    关注

    Change the lookahead to include the slashes as well:

    ~.*?(?=/hello/)~i
    

    Code:

    var_dump(preg_match('~.*?(?=/hello/)~i', $string));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

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

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

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

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

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

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

客服 返回
顶部