[英]preg match with html tag mailto
我有以下代码,我想捕获一个以 ** Data Contact: ** 开头的值,因为我需要在文本中找到 email 地址。
我的代码在没有 html 时有效,但我不知道如何在预匹配中更改正则表达式,它将在 html 标签中工作。
$text = 'Some text Some text
Data Contact: <a href="mailto:atest@gmail.sbr">atest@gmail.com</a>, <a href="mailto:test@op.eu">test@op.eu</a><br />
<a href="mailto:ag@gmail.eu">ag@gmail.eu</a><br />
Some text Some text Some text';
preg_match_all("/Data Contact: +[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i", $text, $matches);
foreach($matches[0] as $val){
echo str_replace("Data Contact:", "",$val);
}
我可以看到解决此问题的两种可能方法:
<?php
$text = 'Some text Some text
Data Contact: <a href="mailto:atest@gmail.sbr">atest@gmail.com</a>, <a href="mailto:test@op.eu">test@op.eu</a><br />
<a href="mailto:ag@gmail.eu">ag@gmail.eu</a><br />
Some text Some text Some text';
preg_match_all("/Data Contact: +\K[-.\w]+@[-.\w]+/i", strip_tags($text), $matches);
foreach($matches[0] as $val){
echo $val;
}
这似乎与问题的描述相匹配。 我们剥离 HTML 上下文,然后在Data Contact:
之后拉取 email。
或者,可以使用 HTML 解析器使用mailto:
上下文提取每个链接,这与问题的标题匹配:
$text = 'Some text Some text
Data Contact: <a href="mailto:atest@gmail.sbr">atest@gmail.com</a>, <a href="mailto:test@op.eu">test@op.eu</a><br />
<a href="mailto:ag@gmail.eu">ag@gmail.eu</a><br />
Some text Some text Some text';
$dom = new DOMDocument;
$dom->loadHTML($text);
$links = $dom->getElementsByTagName('a');
foreach($links as $link){
$href = $link->getAttribute('href');
if(strpos($href, 'mailto:') !== FALSE){
echo str_replace('mailto:', '', $href);
}
}
更新,对于更新的要求:
<?php
$text = 'Some text Some text
Data Contact: <a href="mailto:atest@gmail.sbr">atest@gmail.com</a>, <a href="mailto:test@op.eu">test@op.eu</a><br />
<a href="mailto:ag@gmail.eu">ag@gmail.eu</a><br />
Some text Some text Some text';
$emails = preg_replace_callback("/.*Data Contact: +.*/is", function($match){
preg_match_all('/mailto:\K[-.\w]+@[-.\w]+/', $match[0], $matches);
$emails = '';
foreach($matches[0] as $email){
$emails .= $email . PHP_EOL;
}
return $emails;
}, $text);
echo $emails;
找到Data Contact:
首先,然后将每个mailto:
拉到 email 匹配值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.