从php正则表达式中提取匹配项 [英] Extracting matches from php regex

查看:316
本文介绍了从php正则表达式中提取匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在perl正则表达式中,我们可以提取匹配的变量,例如下面.

In perl regex we can extract the matched variables, ex below.

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

如何在php中做到这一点?

How to do this in php?

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

如何从那里提取电子邮件? (我们可以将其爆炸并获得它,但是想要一种直接通过正则表达式获得它的方法)?

How to extract the email from there? (We can explode it and get it...but would like a method to get it directly through regex)?

推荐答案

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

Try using the named subpattern syntax of 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 )

这篇关于从php正则表达式中提取匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆