Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting matches from php regex

Tags:

regex

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;

How to do this in php?

$subject = "E:[email protected] 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)?

like image 404
Natkeeran Avatar asked Sep 29 '09 14:09

Natkeeran


1 Answers

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);

?>

Output:

 Array (
     [0] => foobar: 2008
     [name] => foobar
     [1] => foobar
     [digit] => 2008
     [2] => 2008 )
like image 119
Chris Rasco Avatar answered Oct 15 '22 16:10

Chris Rasco