【问题标题】:need some help on regex in preg_match_all()在 preg_match_all() 中需要一些关于正则表达式的帮助
【发布时间】:2017-10-02 16:41:27
【问题描述】:

所以我需要从字符串中提取票号“Ticket#999999”.. 我如何使用正则表达式来做到这一点。

如果我在 Ticket#9999 中有多个号码,我当前的正则表达式正在工作。但如果我只有 Ticket#9,则它不起作用,请帮忙。

当前的正则表达式。

 preg_match_all('/(Ticket#[0-9])\w\d+/i',$data,$matches);

谢谢。

【问题讨论】:

  • 可能会提供更好/更有效的答案,但在您提供完整的输入字符串之前我们不会知道。我们知道您的输入字符串可以是Ticket#9,但是当您有多个票证子字符串要捕获时,我们不知道您的输入字符串是什么样子。请编辑您的问题以澄清您的问题。

标签: php regex preg-match-all


【解决方案1】:

在您的模式中,[0-9] 匹配 1 个数字,\w 匹配另一个数字,\d+ 匹配 1+ 个数字,因此在 # 之后需要 3 个数字。

使用

preg_match_all('/Ticket#([0-9]+)/i',$data,$matches);

这将匹配:

  • Ticket# - 文字字符串 Ticket#
  • ([0-9]+) - 第 1 组捕获 1 个或多个数字。

PHP demo:

$data = "Ticket#999999  ticket#9";
preg_match_all('/Ticket#([0-9]+)/i',$data,$matches, PREG_SET_ORDER);
print_r($matches);

输出:

Array
(
    [0] => Array
        (
            [0] => Ticket#999999
            [1] => 999999
        )

    [1] => Array
        (
            [0] => ticket#9
            [1] => 9
        )

)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-30
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多