[英]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;
}
}
我需要這樣的結果:
href=/public/coursecontent/2017-08-03-12-bhnhlwdjzyblelskiard.docx
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.