PHP提取字符串的一部分

PHP提取字符串的一部分,php,substr,Php,Substr,我必须从以下字符串中提取电子邮件: $string = 'other_text_here to=<my.email@domain.fr> other_text_here <my.email@domain.fr> other_text_here'; $string='other_text_here to=other_text_here other_text_here'; 服务器向我发送日志,并且我有这种格式,我如何才能在没有“to=”的情况下将电子邮件放入变量中 更新:

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

$string = 'other_text_here to=<my.email@domain.fr> other_text_here <my.email@domain.fr> other_text_here';
$string='other_text_here to=other_text_here other_text_here';
服务器向我发送日志,并且我有这种格式,我如何才能在没有“to=”的情况下将电子邮件放入变量中

更新:我已经更新了这个问题,似乎可以在字符串中多次找到电子邮件,而常规的表达式将不能很好地使用它。

如果您确定字符串中的
没有在其他任何地方使用,那么就很容易了:

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
if(preg_match_all('/',$string,$emails)){
array_shift($emails);//从数组中取出第一个匹配项(整个字符串)
}
//$emails现在是字符串中存在的电子邮件数组

括号告诉它捕获
$matches
数组。
*
拾取任何字符,而
告诉它不要贪心,因此
不会被拾取。

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

$string = 'other_text_here to=<my.email@domain.fr> other_text_here';
preg_match( "/\<(.*)\>/", $string, $r );
$email = $r[1];
$string='other_text_here to=other_text_here';
预匹配(“/\/”,$string,$r);
$email=$r[1];
当您
回显$email
时,您将获得我的
。email@domain.fr“

试试这个:

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

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

$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];
$string='other_text_here to=other_text_here';
preg_match('/to=/i',$string,$matches);
echo$匹配[1];

它还不允许我接受回答,我会尽快做,因为我已经更新了问题,我发现服务器可以多次打印到该电子邮件的日志中,并且在这种情况下,常规的扩展无法正常工作。这里的其他解决方案使用(.*),这对于大多数正则表达式来说是非常正确的,处理电子邮件地址后的松散前导或尾随<和>。然而,在我看来,除非你从一个文本块中提取一堆电子邮件,否则你不能在这里预期这些字符,所以你无论如何都需要另一种方法。换句话说,有一个合理的格式限制预期。