【问题标题】:Regular expression to search word in text and not as part of a string (preg_match_all)正则表达式在文本中搜索单词而不是作为字符串的一部分 (preg_match_all)
【发布时间】:2021-10-02 14:45:46
【问题描述】:

我希望任何人都可以帮助我解决这个问题。

我正在寻找的是在一个字符串中搜索一个单词

$text = 'is Apple, name testintapple test APPLE name test';
preg_match_all('/apple/i', $text, $output_array);

返回

array(
0   =>  Apple
1   =>  apple
2   =>  APPLE
)

我希望这只是返回:

array(
0   =>  Apple
1   =>  APPLE
)

【问题讨论】:

  • 我知道您的问题已得到解答,但我给您留下了一个简单的网站,您可以在其中学习并尝试将正则表达式应用于您的应用程序regex101.com
  • @Chaturrin 如果能解决您的问题,请检查答案并点赞/接受?

标签: php regex preg-match-all


【解决方案1】:

你需要的是:

preg_match_all('/\bapple\b/i', $text, $output_array);

\b 是一个单词边界。所以它只会在 apple 用作单词而不是更大字符串的一部分时匹配。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多