2013-10-16 89 views
1

我必须从以下字符串中提取电子邮件的一个组成部分:PHP提取字符串

$string = 'other_text_here to=<[email protected]> other_text_here <[email protected]> other_text_here'; 

服务器发送我的日志,并在那里,我有这种格式的,我怎么能得到的电子邮件进入没有“到= <”和“>”变量?

更新:我已经更新了这个问题,好像这个电子邮件可以在字符串中找到很多次,并且正常的表达式不能很好地与它一起工作。

if (preg_match_all('/<(.*?)>/', $string, $emails)) { 
    array_shift($emails); // Take the first match (the whole string) off the array 
} 
// $emails is now an array of emails if any exist in the string 

括号告诉它捕捉到了$matches数组:如果您确信<>字符串中,不使用其他任何地方

回答

2

您可以尝试更严格的正则表达式。

$string = 'other_text_here to=<[email protected]> other_text_here'; 
preg_match('/to=<([A-Z0-9._%+-][email protected][A-Z0-9.-]+\.[A-Z]{2,4})>/i', $string, $matches); 
echo $matches[1]; 
0

Regular expression很容易。 .*接收任何字符,并且?告诉它不是贪婪的,所以>不会被拾取。

+0

它不会让我接受answere,但我会尽快完成,thx –

+0

啊,是的好赶上。固定! –

+0

我已经更新了这个问题,我发现服务器可以多次打印到该电子邮件的日志中,并且正常的表达式在这种情况下效果不佳。 –

1

简单的正则表达式应该能够做到这一点:

$string = 'other_text_here to=<[email protected]> other_text_here'; 
preg_match("/\<(.*)\>/", $string, $r); 
$email = $r[1]; 

当你echo $email,你"[email protected]"

+0

这里的其他解决方案使用(。*?),这对大多数正则表达式来说是非常适当的,在电子邮件地址之后处理松散的前导或尾随< and >。但是,在我看来,除非你从一段文本中提取了一堆电子邮件,否则你不能在这里预测这些字符,所以你需要另一种方法。换句话说,对格式限制有一个合理的期望。 – pp19dd

0

试试这个:

<?php 
$str = "The day is <tag> beautiful </tag> isn't it? "; 
preg_match("'<tag>(.*?)</tag>'si", $str, $match); 
$output = array_pop($match); 
echo $output; 
?> 

输出:

美丽