代码之家  ›  专栏  ›  技术社区  ›  Natkeeran

从php正则表达式中提取匹配项

  •  14
  • Natkeeran  · 技术社区  · 16 年前

       # extract hours, minutes, seconds
       $time =~ /(\d\d):(\d\d):(\d\d)/; # match hh:mm:ss format
       $hours = $1;
       $minutes = $2;
       $seconds = $3;
    

    如何在php中实现这一点?

    $subject = "E:contact@customer.com I:100955";
    $pattern = "/^E:/";
    if (preg_match($pattern, $subject)) {
        echo "Yes, A Match";
    }
    

    如何从那里提取电子邮件?(我们可以分解它并得到它…但是想要一个直接通过正则表达式得到它的方法吗)?

    4 回复  |  直到 16 年前
        1
  •  31
  •   Chris Rasco    16 年前

    尝试使用preg_match的命名子模式语法:

    <?php
    
    $str = 'foobar: 2008';
    
    // Works in PHP 5.2.2 and later.
    preg_match('/(?<name>\w+): (?<digit>\d+)/', $str, $matches);
    
    // Before PHP 5.2.2, use this:
    // preg_match('/(?P<name>\w+): (?P<digit>\d+)/', $str, $matches);
    
    print_r($matches);
    
    ?>
    

    输出:

     Array (
         [0] => foobar: 2008
         [name] => foobar
         [1] => foobar
         [digit] => 2008
         [2] => 2008 )
    
        2
  •  9
  •   Yannick Motton    16 年前

    manual

    int preg_匹配(字符串$pattern,字符串$subject[,数组&$matches[,int$flags[,int$offset]]))

    如果提供了匹配项,则它将填充搜索结果。 匹配完整模式,$matches 1 将具有与 第一次捕获括号 子模式,等等。

    $subject = "E:contact@customer.com I:100955";
    $pattern = "/^E:(?<contact>\w+) I:(?<id>\d+)$/";
    if (preg_match($pattern, $subject,$matches)) {
        print_r($matches);
    }
    
        3
  •  3
  •   Josh Davis    16 年前

    您只需修改当前的regexp即可捕获冒号之后直至第一个空格的所有内容:

    $subject = "E:contact@customer.com I:100955";
    $pattern = "/^E:([^ ]+)/";
    if (preg_match($pattern, $subject, $m)) {
        echo "Yes, A Match";
    }
    $email = $m[1];
    

    如果您不熟悉regexp, [^ ]+ 方法 “除空格外的任何字符” 而且它不需要一个空间来工作。如果出于任何原因,输入更改为 “E:email@host.tld" 没有 “I:12345” 但是,它仍然可以工作。

        4
  •  2
  •   ennuikiller    16 年前

    使用preg_match函数的matchs参数,如下所示:

    比赛:

        5
  •  1
  •   Juan Sebastian Contreras Aceve    7 年前

    更简单的解决方案

    1. regex101.com
    2. 使用优秀的文档创建和测试正则表达式(确保选择PHP)。
    3. 工具 部分点击 code generation

    4. 这是我得到的一个例子。

    $re = '/\#.*@hello\((?<operator>\w+),?(?<args>.*)\).*/m';
    $str = ' Testing string
    # @hello(group_fields)
    # @hello(operator, arguments, more arguments)';
    
    preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
    
    // Print the entire match result
    var_dump($matches);