簡體   English   中英

正則表達式從文本中獲取所有href標簽

[英]Regex to get all href tags from text

我的文字很大,其中包含普通文字和href標簽。 我想使用正則表達式檢索所有href標簽。

我嘗試了href="([^"]*)"但它僅返回一個href值。

 $result[] = $util->execute(self::$queryToGetContentFromPagesEng3); //getting text from database
 foreach ($result as $temp) {
   if(preg_match("href=\"([^\"]*)\"",$temp)) {
     $storeUrl []=$temp;
   }
 }

我需要這樣的結果:

  1. href=/public/coursecontent/2017-08-03-12-bhnhlwdjzyblelskiard.docx
  2. href=/public/coursecontent/2016-07-07-07-rncsuatxhkkbeomysbmk.docx

我的第一點是, 在這種情況下正則表達式很可能不是您要采用的路徑

但是繼續進行下去,您可以嘗試使用preg_match_all而不是preg_match來查找多個匹配項並將它們存儲在數組中,然后從您的foreach中運行一個preg_match_all並將其存儲在數組中,並將array_merge合並到$storeUrul數組中。


但是,我相信一種更簡單的方法,最有可能也是更可靠的方法是解析HTML並從DOM中進行工作。 這是一個簡短的指南 ,可以根據您的情況簡化為:

$dom = new DOMDocument();
$dom->loadHTML($result);
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("a");

for($i = 0; $i < $hrefs->length; $i++){
    $href = $hrefs->item($i);
    $url = $href->getAttribute('href');
    $storeUrl[] = $url;
}

由於標題是js正則表達式...

 const myString = '...'
 const regex = /href=".+?"/gi;
 const regex2 = /(?<=href=").+?(?=")/gi;
 //regex2 is without 'href' and "
 myString.match(regex);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM