[英]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.