首页 > 解决方案 > 正则表达式:在 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]' 的链接

不应选择 的链接:包含空方括号 [] 的链接。

标签: phpregexregex-lookaroundsregex-group

解决方案


您可以使用 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
    }
}

推荐阅读