【问题标题】:How to match full words?如何匹配完整的单词?
【发布时间】:2011-01-06 04:34:49
【问题描述】:

我使用简单的preg_match_all 来查找文本中单词列表的出现。

$pattern = '/(word1|word2|word3)/';
$num_found = preg_match_all( $pattern, $string, $matches );

但这也匹配像abcword123 这样的单词子集。当word1word2word3 仅作为完整单词出现时,我需要它来查找它们。请注意,这并不总是意味着它们在两边都用空格分隔,它可以是逗号、分号、句号、感叹号、问号或其他标点符号。

【问题讨论】:

    标签: php regex search


    【解决方案1】:

    如果您只想匹配“word1”、“word2”、“word3”等,那么使用 in_array 总是更好。正则表达式非常强大,但它也需要大量的 cpu 能力。所以尽量避免它

    $words = array ("word1", "word2", "word3" );
    $found = in_array ($string, $words);
    

    查看PHP: in_array - Manual以获取有关in_array的更多信息

    如果您只想使用正则表达式,请尝试

    $pattern = '/^(word1|word2|word3)$/';
    $num_found = preg_match_all( $pattern, $string, $matches );
    

    如果你想得到"this statement has word1 in it" 之类的东西,请使用"\b" 之类的东西

    $pattern = '/\b(word1|word2|word3)\b/';
    $num_found = preg_match_all( $pattern, $string, $matches );
    

    更多内容在这里PHP: Escape sequences - Manual搜索\b

    【讨论】:

      【解决方案2】:

      试试:

      $pattern = '/\b(word1|word2|word3)\b/';
      $num_found = preg_match_all( $pattern, $string, $matches );
      

      【讨论】:

        【解决方案3】:

        您可以使用\b 来匹配单词边界。所以你想使用/\b(word1|word2|word3)\b/ 作为你的正则表达式。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-12-16
          • 2013-11-28
          相关资源
          最近更新 更多