0

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.

3
  • why negetive?? this is genuine question Commented Aug 19, 2017 at 12:18
  • You don't need regex for that: $name = strtok($data['From'], '<'); Commented Aug 19, 2017 at 12:25
  • @MagnusEriksson , i am already using a regex to get email id , so it's better for me to use it in one condition and get both name and email address Commented Aug 19, 2017 at 12:26

5 Answers 5

3

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]);
Sign up to request clarification or add additional context in comments.

4 Comments

How to implement it in php?
added to answer
Why are you using preg_match_all? preg_match is suffficient.
yes, edited, wasn't familiar with the php syntax used the code generator in regex101
2

Use this in php

$data['From'] = "chirag patel <[email protected]>";
preg_match("/.*(?=\<(.*)\>)/", $data['From'], $matches);
print_r($matches); // 0 : name, 1 : email

Comments

2

You add a capturing group for the name.

preg_match("/(.*)\<(.*)\>/", $data['From'], $matches);
$name = $matches[1];
$email = $matches[2];

Comments

2

You may use this regex to capture name and email address in 2 separate groups:

(\pL+[\pL\h.-]*?)\h*<([^>]+)>

RegEx Demo

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 > characters

Code:

preg_match('~(\pL+(?:[\pL\h-]*\pL)?)\h*<([^>]+)>~u', $str, $matches);

// Print the entire match result
print_r($matches);

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.