dongsheng66783619 2019-03-10 04:09
浏览 209
已采纳

正则表达式获取仅包含模式列表中的单词的字符串?

Consider the following array elements

 1.benclinton
 2.clintonharry
 3.harryben
 4.benwill
 5.jasonsmith
 6.smithclinton

Assume the pattern list is ben,harry,clinton, then the result I should get is

1.benclinton  
2.clintonharry  
3.harryben

So,essentially the result should contain strings that contains only the words that are in the pattern list. Order is not important

Also, each strings will not be having more than two words. i.e. bensmithwill will never be a case.

Since all my strings are in an array, I thought of using preg_grep in php to do this but i am struck in framing correct regex for this.

what regex can achieve this? Is there any other efficient way apart from regex matching that will do the work?

Thanks in advance!

  • 写回答

3条回答 默认 最新

  • dongtan8122 2019-03-10 04:36
    关注

    Something like this

    $names_list = ['benclinton','clintonharry','harryben','benwill','jasonsmith','smithclinton'];
    $names = ['ben','harry','clinton'];  
    
    $matches = preg_grep('/('.implode('|',$names).')(?1)/', $names_list);
    //-  /(ben|harry|clinton)(?1)/  -- (?1) = recurse capture group 1 
    
    print_r($matches);
    

    Output

    Array
    (
        [0] => benclinton
        [1] => clintonharry
        [2] => harryben
    )
    

    Sandbox

    This requires that at least two of the names (even the same one 2x) match. But that is kind of a given in this case or everything would match.

    If you want to be extra careful, if the $names can contain something important to regex, such as +,*, \ etc. you can add this

    $matches = preg_grep('/('.implode('|',array_map(function($name){return preg_quote($name,'/');},$names)).')(?1)/', $names_list);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果