php - 正则表达式:在 html 中查找不包含方括号和文本的链接,例如。'[Some_Random_text]' 但可以包含空方括号 '[]'
问题描述
情况1:
示例 html:<a href="https://www.jessussaveme.com/saveme/c-from.html?random[for_god_sake_save_me]=anyonethere&no=fr&lang=fr">Test</a>
预期输出:
https://www.jessussaveme.com/saveme/c-from.html?random[for_god_sake_save_me]=anyonethere&no=fr&lang=fr
案例二:
示例 html:<a href="https://www.jessussaveme.com/saveme/c-from.html?random[]=anyonethere&no=fr&lang=fr">Test</a>
预期输出:没有。链接不应包含空方括号 []
案例3:
示例 html:<a href="https://www.jessussaveme.com/saveme/c-from.html?random=anyonethere&no=fr&lang=fr">Test</a>
预期输出:https://www.jessussaveme.com/saveme/c-from.html?random=anyonethere&no=fr&lang=fr
应该选择哪些链接: 1. 不包含任何方括号 '[]' 的 链接或 2. 包含非空方括号 '[Some_random_text]' 的链接
不应选择 的链接:包含空方括号 [] 的链接。
解决方案
您可以使用 jQuery 而不是正则表达式:
$("a").each(function(index) { // iterates all <a> elements
console.log($(this).attr('href').includes('[]') ? '' : $(this).attr('href')); // check if contain "[]" or not.
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="https://www.jessussaveme.com/saveme/c-from.html?reges[for_god_sake_save_me]=anyonethere&no=fr&lang=fr">Test</a>
<a href="https://www.jessussaveme.com/saveme/c-from.html?reges[]=anyonethere&no=fr&lang=fr">Test</a>
<a href="https://www.jessussaveme.com/saveme/c-from.html?random=anyonethere&no=fr&lang=fr">Test</a>
除非您可以从a href
您那里获取文本,否则不应使用正则表达式来解析.
由于您已经说过您使用 PHP,您可以尝试以下方法来提取 URL:
$html = '<a href="https://www.jessussaveme.com/saveme/c-from.html?reges[for_god_sake_save_me]=anyonethere&no=fr&lang=fr">Test</a>
<a href="https://www.jessussaveme.com/saveme/c-from.html?reges[]=anyonethere&no=fr&lang=fr">Test</a>
<a href="https://www.jessussaveme.com/saveme/c-from.html?random=anyonethere&no=fr&lang=fr">Test</a>';
$hrefs = array();
$dom = new DOMDocument();
$dom->loadHTML($html);
$tags = $dom->getElementsByTagName('a');
foreach ($tags as $tag) {
$hrefs[] = $tag->getAttribute('href');
}
并检查是否包含空括号:
foreach($hrefs as $a)
{
if (strpos($a, '[]') == false) {
echo 'true'; // doesn't contain empty bracket
}
}
推荐阅读
- gpsd - gpsd ttyACM0 没有这样的设备
- html - 卡片视图的背景图像未显示
- r - Tukey HSD 用于 R 中的分类和连续变量
- python-3.x - ModuleNotFoundError:没有名为“pyproj.crs.crs”的模块;“pyproj.crs”不是一个包
- django - Django:获取第二个用户对象
- html - 宽度变化时进度点的位置没有正确对齐
- php - 使用 Laravel 在控制器中使用私有变量
- javascript - 展开和折叠 HTML 表数据行
- python - 试图改变列表失败
- streamlit - 有没有办法在流光中更改微调器的占位符文本?