繁体   English   中英

PHP提取字符串的一部分

[英]PHP extract one part of a string

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

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

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

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

您可以尝试使用限制性更强的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];

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

$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"

如果您确定<>未在字符串中的任何其他位置使用,则正则表达式将很容易:

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数组。 .*拾取任何字符和? 告诉它不要贪心,所以>没有拿起它。

尝试这个:

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

输出:

美丽

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM