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 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!