php preg_replace string extract
Original regexp:
$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 开发者_Python百科only => <bar@baz.com>
Thanks
Okay, so it looks like you are wanting to get a value, rather than replace a value, so you should be using preg_match, not preg_replace (though technically you could use preg_replace in a round-about way...)
preg_match('~(?:"([^"]*)")?\s*(.*)~',$str,$match);
$var = ($match[1])? $match[1] : $match[2];
You need to require something inside the quotes when you do the replace.
$str = '"foo" <bar@baz.com>';
preg_replace('/"([^"]+)"\s(<.*?>)/', '$1', $str);
preg_replace('/""\s(<.*?>)/', '$1', $str);
Try that. It should leave the address alone if there's no quoted name before it.
Edit: Based on your new example inputs and outputs, try this:
$str = '"foo" <bar@baz.com>';
preg_replace('/"([^"]+)"\s(<.*?>)/', '$1', $str);
preg_replace('/(?:""\s)?(<.*?>)/', '$1', $str);
It should have the following input/output results:
"foo" <bar@baz.com> -> foo
"" <bar@baz.com> -> <bar@baz.com>
<bar@baz.com> -> <bar@baz.com>
精彩评论