我有这个正则表达式来匹配 HTML 代码中的图像 URL:
$regex = '#[\w,=/:.-]+\.(?:jpe?g|png|gif)#iu';
Php demo :
$input = <<<HTML
<a href="https://e...content-available-to-author-only...e.com/example1.jpg">
<a href="https://e...content-available-to-author-only...e.com/ストスト.jpg">
<a href="https://e...content-available-to-author-only...e.com/example3.jpg">
<a href="https://e...content-available-to-author-only...e.com/example3.bak">
HTML;
$dom = new DomDocument();
$dom->loadHTML(mb_convert_encoding($input, 'HTML-ENTITIES', "UTF-8"));
$anchors = $dom->getElementsByTagName("a");
$regex = '#^[\w,=/:.-]+\.(?:jpe?g|png|gif)$#iu';
foreach ($anchors as $anchor) {
$res = $anchor->getAttribute("href");
if (preg_match($regex, $res)) {
echo "Valid url: $res" . PHP_EOL;
} else {
echo "Invalid url: $res" . PHP_EOL;
}
}
我的问题是,如何让它只匹配以 http
或 //
开头的。目前它与 example.jpg
匹配,它不是完整的 URL。
最佳答案
我建议这样的模式:href="((?:http|\/\/)[^"]+\.(?:jpe?g|png|gif))"
解释:
href="
- 从字面上匹配 href="
,它将确保您匹配超链接
(...)
- 捕获组以存储实际链接
(?:...)
- 非捕获组
http|\/\/
- 匹配 http
或 //
[^"]+
- 匹配 "
\.
- 按字面匹配 .
jpe?g|png|gif
- 改变,匹配选项 jpeg
、jpg
中的一个(由于 e?
), png
, gif
"
- 按字面匹配 "
匹配的链接将在第一个捕获组内。
关于regex - 仅匹配以字符开头的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60452074/