2011-05-04 69 views
3

原正则表达式:PHP的preg_replace字符串中提取

$str = '"foo" <[email protected]>'; 
preg_replace('/\s(<.*?>)|"/', '', $str); 

我想提取以下内容:

"foo" <[email protected]> extract only => foo 
<[email protected]>  extract only => <[email protected]> 
"" <[email protected]> extract only => <[email protected]> 

感谢

+0

你能澄清一下你实际上是想在这里做什么?因为如果你正试图*取*值,preg_replace()并不是真正的正确函数... – 2011-05-04 14:08:26

+0

@蜡笔:问题更新 – 2011-05-04 14:13:44

回答

0

你需要需要引号里面的东西,当你替换。

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

试试看。如果在它之前没有引用的名称,它应该单独留下地址。

编辑:根据您的新的例子输入和输出,试试这个:

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

它应具有以下输入/输出结果:

"foo" <[email protected]> -> foo 
"" <[email protected]>  -> <[email protected]> 
<[email protected]>  -> <[email protected]> 
+0

有没有一种方法来提取名称只有在引号之间,而不是两个? – 2011-05-04 14:10:24

+0

@Mike - 不知道我明白。你能解释一下你的意思吗?上面的代码应该将''foo'<[email protected]>'变成'foo',并且''“<[email protected]>'变成'<[email protected]>'。 – 2011-05-04 14:14:06

+0

@Justin:我已经更新了我的问题:) – 2011-05-04 14:18:24

3

好了,所以它看起来像你想获得的一个值,而不是取代一个值,所以你应该使用preg_match,而不是preg_replace(虽然技术上你可能使用的preg_replace以迂回的方式......)

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