Reputation: 1937
I have no idea how to make a regex , that's why i am asking this question.I have one string like chirag patel <[email protected]>
I have a regex to get email id from the string.
preg_match("/\<(.*)\>/", $data['From'], $matches);
$email = $matches[1];
How to get name from above string using regex?
my expected output is: chirag patel
.
Upvotes: 0
Views: 191
Reputation: 2294
I know it has been answered but because it's in PHP, which supports named patterns, and because might look cool:
/(?<name>.*?) \<(?<email>.*?)\>/g
name and email will be keys in the $matches array.
Upvotes: 2
Reputation: 10458
You can use the regex
.*(?=\<(.*)\>)
check the demo here. here is the php code for the following
$re = '/.*(?=\<(.*)\>)/';
$str = 'chirag patel <[email protected]>';
preg_match($re, $str, $matches);
var_dump($matches[0]);
Upvotes: 3
Reputation: 785266
You may use this regex to capture name and email address in 2 separate groups:
(\pL+[\pL\h.-]*?)\h*<([^>]+)>
RegEx Breakup:
(\pL+[\pL\h.-]*?)
# group #1 that match 1+ name consisting Unicode letters, dots, hyphens, spaces\h*
: Match 0 or more whitespaces<([^>]+)>
: group #2 to capture email address between <
and >
charactersCode:
preg_match('~(\pL+(?:[\pL\h-]*\pL)?)\h*<([^>]+)>~u', $str, $matches);
// Print the entire match result
print_r($matches);
Upvotes: 2
Reputation: 5589
You add a capturing group for the name.
preg_match("/(.*)\<(.*)\>/", $data['From'], $matches);
$name = $matches[1];
$email = $matches[2];
Upvotes: 2
Reputation: 16436
Use this in php
$data['From'] = "chirag patel <[email protected]>";
preg_match("/.*(?=\<(.*)\>)/", $data['From'], $matches);
print_r($matches); // 0 : name, 1 : email
Upvotes: 2