【问题标题】:Need to extract words from string in php [duplicate]需要从php中的字符串中提取单词[重复]
【发布时间】:2014-11-29 04:48:06
【问题描述】:

我需要从以下字符串中提取名称:

$contact = "John96783819Dickson97863424"

我试过用这个:

preg_match('/[a-zA-Z]/',$contact,$matches);

但我得到了一个数组,其中所有字母都单独包含在数组中。

期望的输出:

Array ([0] => 'John', [2] => 'Dickson')

现在它变得复杂了。同样的雷鬼应该提取这个

$contact = 'Vincent Tan96123179Lawrence Thoo90603123Ryan Ong91235721' 进入这个

Array ([0] => 'Vincent Tan', [2] => 'Lawrance Thoo' , [3] => 'Ryan Ong')

我该怎么做?

【问题讨论】:

  • 好的,找到了我的问题的答案。 [a-z A-Z]+ 可以解决问题

标签: php regex


【解决方案1】:

您只需要使用+量化字符类

/[a-zA-Z]+/
  • + 匹配出现的前一个正则表达式

例如:http://regex101.com/r/bI6aH1/1

preg_match_all('/[a-zA-Z]+/',$contact,$matches);

将输出为

Array ( [0] => John [1] => Dickson )

【讨论】:

  • preg_match_all
【解决方案2】:
 preg_match('/[a-zA-Z]+/',$contact,$matches);

/[a-zA-Z]/ 表示匹配字符串中任意一个字母。在 /[a-zA-Z]+/ 中添加 + 表示匹配一个或多个连续字母。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-21
    • 2021-09-23
    • 2017-11-09
    • 2017-02-04
    • 2011-04-21
    • 2019-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多