php正则表达式从href提取特定域(带/不带www-http-https)
我正在尝试检查包含特定域的a标记。。。但是这个标签可能有或没有php正则表达式从href提取特定域(带/不带www-http-https),php,regex,Php,Regex,我正在尝试检查包含特定域的a标记。。。但是这个标签可能有或没有www,hhtp,https $a = ' <a href="https://example.com"></a> <a href="http://www.example.com"></a> <a href="http://example.com"></a> <
www
,hhtp
,https
$a = ' <a href="https://example.com"></a>
<a href="http://www.example.com"></a>
<a href="http://example.com"></a>
<a href="https://www.example.com"></a>
<a href="http://example.com"></a>
';
$reg_exUrl = "/(http|https)\:\/\/(www.)?example+\.com(\/\S*)?/";
preg_match($reg_exUrl, $a, $url) ;
var_dump($url);
另外,我不知道如何包括
href
,因此它只会在href内搜索,而不是预匹配
,使用预匹配
UPD:所有url站点正则表达式:
$regex = '/href="(.*?)"/';
使用HTML解析器,然后使用URL解析器来获取域。从这里开始,在受限字符串上使用正则表达式:
$a = ' <a href="https://example.com"></a>
<a href="http://www.example.com"></a>
<a href="http://example.com"></a>
<a href="https://www.example.com"></a>
<a href="http://example.com"></a>
';
$dom = new DOMDocument;
$dom->loadHTML($a);
$links = $dom->getElementsByTagName('a');
foreach($links as $link) {
$host = parse_url($link->getAttribute('href'))['host'];
if(!empty($host) && preg_match('/(^|\.)example\.com$/', $host)) {
echo 'Expected domain';
}
}
如上所示,您有3个可能的捕获组。您可以在它们的开头使用?:
,这样它就不会被捕获。您可以将http | https
简化为https?
(?
使s
成为可选的。这里您有:
$a = ' <a href="https://example.com"></a>
<a href="http://www.example.com"></a>
<a href="http://example.com"></a>
<a href="https://www.example.com"></a>
<a href="http://example.com"></a>
';
$reg_exUrl = "/href=\"(?:https?)\:\/\/(?:www\.)?example\.com\"/";
preg_match_all($reg_exUrl, $a, $url) ;
var_dump($url);
$a=
';
$reg\u exUrl=“/href=\”(?:https?\:\/\/(?:www\)?example\.com\“/”;
preg_match_all($reg_exUrl,$a,$url);
var_dump($url);
thanx,您如何在其中添加href
?这样它只会在href中搜索,而不是整个字符串我已经更新了答案。唯一的问题是转义引号“
>\”
这将比example.com
更匹配。thanx,我知道这一点,但这可能会给我otherexample.com/script.php?link=example.com
或类似的东西,这不是我想要的want@hretic实际上(^ | \)
是您想要的。请参阅,我认为这是所有边缘情况。回答得好。您还可以将所有测试部分移动到函数中,并使用XPath查询,请参阅
$reg_exUrl = "/(http|https)\:\/\/(www.)?example+\.com(\/\S*)?/";
^^^^^^^^^^ ^^^^ ^^^^^
$a = ' <a href="https://example.com"></a>
<a href="http://www.example.com"></a>
<a href="http://example.com"></a>
<a href="https://www.example.com"></a>
<a href="http://example.com"></a>
';
$reg_exUrl = "/href=\"(?:https?)\:\/\/(?:www\.)?example\.com\"/";
preg_match_all($reg_exUrl, $a, $url) ;
var_dump($url);