[英]Retrieve all <a href=....jpg"> tags in PHP
$regex = '/<a href=\"([^\"]*)\">(.*)<\/a>/iU';
但它總是無法檢索到我想要的標簽。
它總是錯過以下標簽:
<a href="http://site.com/folder/img1.jpg" name="test">
它還會檢索那些我不想要的,例如:
<a href="mailto:helloworld@hotmail.com">
和
<a href="http://site.com/folder/index.html">
如何修改我的正則表達式,以便它檢索所有<a href="....jpg"
並且如果我得到以下內容:
<a href="http://site.com/folder/img1.jpg" name="test">
它只會顯示
<a href="http://site.com/folder/img1.jpg">
而且它也不會檢索以下內容:
<a href="mailto:helloworld@hotmail.com">
和
<a href="http://site.com/folder/index.html">
謝謝你。
如果能提供有助於生成正則表達式的免費軟件,將不勝感激。
$regex = '/(<a href="([^"]+)\.jpg")[^>]*>/iU';
並替換為“\1>”。
筆記:
"
之前添加一個明確的\.jpg
以僅匹配以.jpg
結尾的鏈接。您可能會考慮\.jpe?g
以允許'.jpeg'和'.jpg'(盡管前者並不常見)<a href=...>
的>
之前添加了一個[^>]*
以允許可選的額外屬性,如name="asdf"
(<a href="xxx")
\1>
(因此去除了所有額外的屬性)。關於正則表達式生成工具,我不知道有任何生成正則表達式的工具。 我認為最好的辦法是自己學習正則表達式,然后使用交互式測試器快速開發它。
如果您點擊該鏈接,您將准確地看到我輸入的正則表達式和一些可以使用它的測試數據。
然后您可以嘗試使用正則表達式並實時查看結果——這對快速開發正則表達式非常有幫助。
(盡管 regexr.com 不提供不受歡迎的“U”標簽;只需將正則表達式中的所有+
轉換為+?
並將*
轉換為*?
即可模擬此操作)。
我不知道你到底在用這個正則表達式做什么,但我認為這對你有用:
$your_string = '<a href="http://site.com/folder/img1.jpg" name="test">';
preg_match('@<a href="(.*?)".*?>(.*<\/a>)?@', $your_string, $matches);
print_r($matches) // Array ( [0] => http://site.com/folder/img1.jpg )
<?php
// set up to parse our input
$dom = new DOMDocument();
$dom->loadHTMLFile("input.html");
$xpath = new DOMXPath($dom);
$anchors = $xpath->query("//a[contains(@href, 'http') and contains(@href, '.jpg')]");
foreach ($anchors as $anchor) {
echo $anchor->C14N() . "\n";
}
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.