2017-07-15 41 views

回答

0

使用regexPHP

$text = '<a href="/contact/new">Contact us</a>'; 

preg_match_all('(<a href="([^"]*)">[Contact us|Contact]*</a>)', $text, $matches); 
foreach ($matches[1] as $href) { 
    // Do whatever you want with the href attribute 
    echo $href; 
} 

使用jQuery

選擇全部a元素,檢查他們的html()就是你正在尋找返回文本attr.("href")

$("a").each(function(index, element) { 
    if ($(elem).html() == "Contact" || $(elem).html() == "Contact us") { 

     // Do whatever you want with the href attribute 
     console.log($(elem).attr("href")); 

    } 
}); 
+0

它的jQuery的,對不對?你可以使用PHP嗎? – prokawsar

+0

你的意思是PHP解析'a'標籤就像一個字符串? –

+0

是的,解析所有'a'標籤。 – prokawsar

0

我已經通過這段代碼解決了。從@Matias獲得方法Cerrotta

foreach($dom->find('a') as $element) { echo $element->plaintext . '<br>'; }

0

後,顯然這可以使用SimpleXML和XPath來完成。

您將需要調整如何使用file_get_contents或其他某種方法將頁面加載到SimpleXML中以將頁面讀取到變量並將其傳遞。

我已經創建了一個模擬了的作品下面

<?php 
$html = ' 
<a href="/contact/new">Contact us</a> 
'; 

//Replace with your loading logic here 
$xml = simplexml_load_string($html); 

//Perform the search 
$search = $xml->xpath('//a[contains(text(), "Contact us") or contains(text(), "Contact")]'); 

//Check the results have at least one value 
if(count($search) !== 0 && $search !== false) 
{ 
    //Get first item 
    $item = $search[0]; 

    //Get item attributes 
    $attributes = $item->attributes(); 

    //Output the HREF attribute (need an existence check here (isset)) 
    echo $attributes['href']; 
} 

中的XPath方法返回,這將需要通過過濾如果返回多於一個的結果匹配的陣列,我抓住樣品中第一個輸出節點的href屬性。

搜索找到所有a標籤,而不管字符串/文檔中的位置,並檢查它是否包含「聯繫我們」或「聯繫人」。

注意: XPath是區分大小寫的,雖然有辦法讓它變得不敏感,但您需要自己實現或者編寫更多的條件來檢查。

如果需要再區分大小寫檢查另一個棧的問題,它已經覆蓋前:

E.g:case insensitive xpath searching in php

相關問題