duanchu7271 2018-03-03 20:27
浏览 445
已采纳

如何使用正则表达式搜索字符串是否包含列表中的至少一个单词?

I have a string and need to check if any of the words in my list are in the string.
My list looks like this:

$keywords = array(
    "l.*ion",
    "test",
    'one',
    'two',
    'three'
);
  1. If I have string This is my lion then I need to return true.
  2. If I have string This is my lotion then I need to return true.
  3. If I have string This is my dandelion then return false.
  4. If I have string This is my location then return true.
  5. If I have string This is my test then return true.
  6. If I have string This is my testing then return false.

This is my code:

$keywords = implode($keywords,"|");
$list= "/\b$keywords\b/i";
$my_string= "This is my testing";
preg_match($list, $my_string, $matches, PREG_OFFSET_CAPTURE);
echo $matches[0][1];

But when I do This is my testing it returns a value.
What am I doing wrong? I'm expecting a numerical value if its true and and error if its false.

  • 写回答

1条回答 默认 最新

  • douliedu335997 2018-03-03 20:57
    关注

    In your current regex, \bl.*ion|test|one|two|three\b, the first \b only affects the first alternative and the last \b only affects the last alternative.

    Besides, since you want to only restrict matching of keywords to a single word, you cannot rely on .* pattern as . matches any char but a line break char.

    You should use either \S* (to match 0+ non-whitespace chars, that also include punctuation) or \w* (to match 0+ letters, digits, and _).

    So, you need to do two things: 1) redefine the $keywords array and 2) use a grouping construct around the alternatives when implodeing to group the alternatives so that the first and last \b could be applied to each alternative.

    $keywords = array(
        "l\w*ion",     // <-- Here, a `\w` is used instead of .
        "test",
        'one',
        'two',
        'three'
    );
    
    $list= "/\b(?:" . implode($keywords,"|") . ")\b/i"; // <-- Here, the (?:...) groups alternatives
    $my_string= "This is my testing";
    if (preg_match($list, $my_string, $matches, PREG_OFFSET_CAPTURE)) {
      echo $matches[0][1];
    }
    

    See the PHP demo.

    Now, the pattern is \b(?:l\w*ion|test|one|two|three)\b and \bs apply to all the alternatives. See this regex demo.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 Windows Server 2016利用兩張網卡處理兩個不同網絡
  • ¥15 Python中knn问题
  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源