【问题标题】:php Exact string match with underscoresphp 与下划线完全匹配的字符串
【发布时间】:2026-01-22 00:25:01
【问题描述】:

我正在尝试对包含特定文本部分的字符串进行精确匹配。 例如字符串是: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("/IMPORT_X_PREMIUM$/~",$str) 应该做您想做的事。
  • @Sherif 这给了preg_match(): Unknown modifier '~'

标签: php regex string-matching


【解决方案1】:

使用

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

regex proof

(?&lt;![^\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

【讨论】:

    最近更新 更多