'; preg_replace('/\s(<.*?>)|"/', '', $str); I would like to extract...">

Fixed php line preg_replace

Original regex:

$str = '"foo" <bar@baz.com>';
preg_replace('/\s(<.*?>)|"/', '', $str);

I would like to extract the following:

"foo" <bar@baz.com> extract only => foo
<bar@baz.com>       extract only => <bar@baz.com>
"" <bar@baz.com>    extract only => <bar@baz.com>

thank

+3
source share
2 answers

When replacing, you should require something inside the quotation marks.

$str = '"foo" <bar@baz.com>';
preg_replace('/"([^"]+)"\s(<.*?>)/', '$1', $str);
preg_replace('/""\s(<.*?>)/', '$1', $str);

Give it a try. He must leave the address alone if no name is given in front of him.

Edit: Based on your new example inputs and outputs, try the following:

$str = '"foo" <bar@baz.com>';
preg_replace('/"([^"]+)"\s(<.*?>)/', '$1', $str);
preg_replace('/(?:""\s)?(<.*?>)/', '$1', $str);

It should have the following I / O results:

"foo" <bar@baz.com>  -> foo
"" <bar@baz.com>     -> <bar@baz.com>
<bar@baz.com>        -> <bar@baz.com>
0
source

So it looks like you want to get the value, not replace the value, so you should use preg_match and not preg_replace (although technically you could use preg_replace in a round way ...)

preg_match('~(?:"([^"]*)")?\s*(.*)~',$str,$match);
$var = ($match[1])? $match[1] : $match[2];
+3
source

All Articles