gpt4 book ai didi

php - preg_match 查找大写单词和连续大写单词

转载 作者:行者123 更新时间:2023-12-04 15:54:49 28 4
gpt4 key购买 nike

我试图通过仅过滤掉符合以下条件的单词来匹配字符串中的关键字:

  • 任何地方都有大写字母的单词,例如“iPhone”或“camelCase”
  • 连续大写的词组,例如“Pittsburgh Steelers”或“Oscar De La Hoya”
  • 结合上述标准,如“iPhone 5”或“MIB 2”(也将数字视为大写)
  • 折叠所有非字符/数字,使“O'Donnell's”成为“ODonnells”,“Wi-fi...”成为“Wifi”

例子:

$string = "Joe O'Donnell and Oscar De La Hoya went to a Pittsburgh Steelers game on Sunday, where Joe lost his iPhone 5, so he borrowed Oscar's iPad";

preg_match_all("/[A-Z][a-z]*/",$string,$match_words); // incorrect expression

// desired result for $match_words should be:
// array(Joe ODonnell, Oscar De La Hoya, Pittsburgh Steelers, Sunday, Joe, iPhone 5, Oscars, iPad)

谢谢

最佳答案

你可以像这样使用正则表达式:

\b((?:[A-Z]['a-z]*\s*\d*)+)\b|\b((?:[a-z]*[A-Z]['a-z]*\s*\d*)+)\b

Working demo

enter image description here

匹配信息:

MATCH 1
1. [0-14] `Joe O'Donnell `
MATCH 2
1. [18-35] `Oscar De La Hoya `
MATCH 3
1. [45-65] `Pittsburgh Steelers `
MATCH 4
1. [73-79] `Sunday`
MATCH 5
1. [87-91] `Joe `
MATCH 6
2. [100-108] `iPhone 5`
MATCH 7
1. [125-133] `Oscar's `
MATCH 8
2. [133-137] `iPad`

正则表达式由两种模式组成:

\b((?:[A-Z]['a-z]*\s*\d*)+)\b       ---> Match words like Joe O'Connels or Oscar De La Hoya
|
\b((?:[a-z]*[A-Z]['a-z]*\s*\d*)+)\b ---> Match words like iPad or iPhone

顺便说一句,如果您查看结果,它末尾有一个尾随空格,您可以对结果进行修剪以将其清理干净。

关于php - preg_match 查找大写单词和连续大写单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26185683/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com