在perl正则表达式中,我们可以提取匹配的变量,如下所示.
# 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"; }
尝试使用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+)/',$matches); print_r($matches); ?>
输出:
Array ( [0] => foobar: 2008 [name] => foobar [1] => foobar [digit] => 2008 [2] => 2008 )