PHP提取字符串的一部分

时间:2013-10-16 13:45:22

标签: php substr

我必须从以下字符串中提取电子邮件:

$string = 'other_text_here to=<my.email@domain.fr> other_text_here <my.email@domain.fr> other_text_here';

服务器发送给我日志,我有这种格式,如何在没有“to =&lt;”的情况下将电子邮件发送到变量中和“&gt;”?

更新:我已经更新了问题,似乎可以在字符串中多次找到该电子邮件,并且常规表达将无法正常使用。

4 个答案:

答案 0 :(得分:2)

您可以尝试使用限制性更强的Regex。

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

答案 1 :(得分:1)

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

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

当您echo $email时,您会获得"my.email@domain.fr"

答案 2 :(得分:0)

如果您确定<>未在字符串中的任何其他位置使用,那么

Regular expression会很简单:

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数组。 .*会收集任何字符,而?会告诉它不要贪婪,因此>不会被捡起来。

答案 3 :(得分: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;
?>

输出:

美丽

相关问题