我会为每个字段使用一个正则表达式:
$match = array();
$regexs = array(
'~Hi\s+(.+?),~', // notice ? -> "greedy killer"
'~Your user ID is: (\d+)~',
'~Your activation ID is: (\d+)~')
if( !preg_match( $regexs[0], $text, $match)){
throw new Exception('Invalid mail format, cannot find user name');
}
// .. and so on for each field
但是,您可以将它们全部放入一个正则表达式中(如果您使用命名的子模式,它将更好地阅读:
$regexp = '~Hi\s+(?P<name>.+?)|Your user ID is: (?P<id>\d+)|Your activation ID is: (?P<activation_id>\d+)~';
$matches = array();
preg_match_all( $regexp, $text, $matches, PREG_SET_ORDER);
foreach( $matches as $match){
print_r( $match);
if( !empty( $match['name'])){
// Having a name
}
}