2011-06-10 71 views
0

我想獲取所有鏈接頁面類「page1」在php。 jQuery中在php中選擇標籤並獲取href

$("a#page1").echo(function() 
{ 
}); 

相同的代碼可以做到這一點在PHP?

$pattern = '`.*?((http|ftp)://[\w#$&+,\/:;[email protected]%.-]+)[^\w#$&+,\/:;[email protected]%.-]*?`i'; 
preg_match_all($pattern,$page_g,$matches); 

此代碼獲取$ page_g中的所有href,但它不適用於class =「page1」。 我只想在$ page_g中的所有href通過class =「page1」 可以幫助我優化請求ex或其他方式嗎? 例如

$page_g="<a href="/?s=cache:16001429:office+s01e02" title="" class="big">the <strong>office</strong> us s01 05 xvid mu</a> <a href="asd.com" class="a">asd</a>"; 

我想只返回/ S =緩存:16001429:辦公+ S01E02 TNX

+0

,但我無法在搜索中打開它。任何人都能找到它?這是關於選擇所有''標籤與PHP – 2011-06-10 13:14:03

+1

你的意思是'a.page1'而不是'#page1'? – 2011-06-10 13:46:56

回答

2

編輯自您澄清問題後進行編輯。

要獲得所有<a>鏈接與類.page1

// Load the HTML from a file 
$your_HTML_string = file_get_contents("html_filename.html"); 

$doc = new DOMDocument(); 
$doc->loadHTML($your_HTML_string); 

// Then select all <a> tags under #page1 
$a_links = $doc->getElementsByTagName("a"); 

foreach ($a_links as $link) { 
    // If they have more than one class, 
    // you'll need to use (strpos($link->getAttribute("class"), "page1") >=0) 
    // instead of == "page1" 

    if ($link->getAttribute("class") == "page1") { 
    // do something 
    } 
} 
+0

我通過fopen閱讀頁面如何進入該文檔? – naser 2011-06-10 13:17:59

+0

@ naser而不是'fopen()',它需要'fread()'和一個while循環,用'file_get_contents()'加載它。它將它作爲字符串返回,然後在我的示例中用作$ your_HTML_string。見上面的編輯。 – 2011-06-10 13:20:14

3

你缺乏專業知識,使用正則表達式爲。因此,在這裏使用DOMdocument是最好的解決方案。如果你想有一個簡單的API,然後使用jQuery的真人秀phpQueryQueryPath

$link = qp($html)->find("a#page1")->attr("href"); 
print $link; 
0

DOM最好用在這裏,因爲正則表達式是難以維持,如果底層的HTML的變化,此外,DOM可以處理無效的HTML併爲您提供訪問其他HTML解析相關工具的權限。

因此,假設有一個包含HTML文件,並且您正在搜索類,這可能是要走的路:我知道這個確切的問題已經被問在過去的幾天裏

$doc = new DOMDocument; 
$doc->load(PATH_TO_YOUR_FILE); 
//we will use Xpath to find all a containing your class, as a tag can have more than one class and it's just easier to do it with Xpath. 
$xpath = new DOMXpath($doc); 
$list = $xpath->query("//a[contains(@class, 'page1')]"); 
foreach ($list as $a_tag) { 
    $href = $a_tag->getAttribute('href'); 
    //do something 
}