PHP 正则表达式,用于从 href 中提取带有/不带 www https 的特定域



im 试图检查包含特定域的 a 标签...但这个标签可能带有或不带wwwhhtphttps

$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);

但我没有得到所有的链接,这是输出

array:2 [▼
0 => "https://example.com"
1 => "https"
]

我也不确定如何包含href,所以它只会在 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';
} 
}

还要解释更多关于您当前输出的信息......preg_match输出找到的第一个匹配项,每个索引是一个捕获组。

$reg_exUrl = "/(http|https)://(www.)?example+.com(/S*)?/";
^^^^^^^^^^        ^^^^                ^^^^^

因此,如上所示,您有 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);

而不是preg_match,使用preg_match_all

UPD :所有网址网站正则表达式:

$regex = '/href="(.*?)"/';

最新更新