php 带下划线的精确字符串匹配

php Exact string match with underscores

我正在尝试对包含特定文本部分的字符串进行精确匹配。 例如字符串是:CAR_NW_BMW_X3_21_01_IMPORT_X_PREMIUM

字符串改变了,但只有最后一部分; IMPORT_X_PREMIUM 所以它可能是 IMPORT_Y_PREMIUM 基于此,我想检查完整字符串中是否存在该部分。

我试过 preg_match 但这不起作用,我不是正则表达式专家所以我可能犯了一个错误。

$str = "CAR_NW_BMW_X3_21_01_IMPORT_X_PREMIUM"
preg_match("~\bIMPORT_X_PREMIUM\b~",$str)

这是如何实现的?

使用

preg_match("~(?<![^\W_])IMPORT_X_PREMIUM(?![^\W_])~",$str)

参见 regex proof

(?<![^\W_])...(?![^\W_]) 是排除 _.

的单词边界

同时考虑:

preg_match("~(?<=\b|_)IMPORT_X_PREMIUM(?=_|\b)~",$str)

参见another regex proof。意思,要么分词,要么下划线。

解释

--------------------------------------------------------------------------------
  (?<!                     look behind to see if there is not:
--------------------------------------------------------------------------------
    [^\W_]                   any character except: non-word
                             characters (all but a-z, A-Z, 0-9, _),
                             '_'
--------------------------------------------------------------------------------
  )                        end of look-behind
--------------------------------------------------------------------------------
  IMPORT_X_PREMIUM         'IMPORT_X_PREMIUM'
--------------------------------------------------------------------------------
  (?!                      look ahead to see if there is not:
--------------------------------------------------------------------------------
    [^\W_]                   any character except: non-word
                             characters (all but a-z, A-Z, 0-9, _),
                             '_'
--------------------------------------------------------------------------------
  )                        end of look-ahead