亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

正則表達式:在 html 中查找不包含方括號和文本的鏈接,例如。

正則表達式:在 html 中查找不包含方括號和文本的鏈接,例如。

PHP
開滿天機 2022-05-27 13:17:00
情況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]' 的鏈接不應選擇 的鏈接:包含空方括號 [] 的鏈接。
查看完整描述

2 回答

?
繁花如伊

TA貢獻2012條經驗 獲得超12個贊

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

    }

}


查看完整回答
反對 回復 2022-05-27
?
牧羊人nacy

TA貢獻1862條經驗 獲得超7個贊

這個有效:


<\S.*?=\"(.*reges\[\w+\].*)\">.*>


你可以看到它在這里工作。它只匹配組 1 中的第一個標簽,并且在 [ ] 為空時在第二種情況下不返回任何內容。


https://regex101.com/r/cdvVnP/1


編輯:


對于第三種情況,它應該類似于以下內容:


if( !str.contains("reges[")){

  //passed() -pick up tat link as string doesnt contain reges[] or reges [some text]

}else{

//match with <\S.*?=\"(.*reges\[\w+\].*)\">.*>

// if you find match then pickup that link from group 1

}


查看完整回答
反對 回復 2022-05-27
  • 2 回答
  • 0 關注
  • 149 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號