duanhe0817825 2017-04-17 19:42 采纳率: 100%
浏览 63
已采纳

特定单词的php请求,但可以用空格分隔

I have a question concerning regex, i.e. with the syntax that works with php. I know some basics about regex in php, so I know that I can match something with

preg_match("/[maxmustermann ]/u", $input_line, $output_array);

Now I want to match all text which contains optional several words which by could be seperated by an space.

Sorry I just dont know how to ask. I try to make an example. I have this text and want to match all the bold ones.

orem ipsum dolor sit amet, consectetur max adipiscing elit. Proin maxm pellentesque dui maxmustermann eu erat mustermann rhoncus tempor sit amet quis odio. Max Mustermann habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Max Muster Mann et malesuada fames ac ante ipsum primis in faucibus. Nam vitae nisl dui.

That means I have this two words: max and mustermann and I want to match words (one ore more) which containing the letters of max and/or mustermann in the order how they are but also random placed space.

Thank you

  • 写回答

3条回答 默认 最新

  • drsrq26482 2017-04-17 20:04
    关注

    You can't do that with regex only. You need first to extract all words composed with your selected letters, and in a second time you have to filter these words. Something like this:

    $word = 'maxmustermann';
    preg_match_all('~\b[aemnrstux]+\b~ui', $txt, $matches);
    
    $result = array_filter($matches[0], function ($i) use ($word) {
        return stripos($word, $i) !== false;
    });
    

    demo

    You can proceed a similar way if you want to perform a replacement:

    $word = 'maxmustermann';
    $result = preg_replace_callback('~\b[aemnrstux]+\b~ui', function ($m) use ($word) {
        return stripos($word, $m[0]) !== false ? "#{$m[0]}#" : $m[0];
    }, $txt);
    

    demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号