Extracting matches from php regex

Viewed 37234

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: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)?

5 Answers

The simpler solution

  1. go to regex101.com
  2. Use the great documentation for creating and testing your regex (make sure you select PHP).
  3. In the TOOLS section click on code generation

  4. This is an example of what I got.

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