2013-05-09 149 views
-1

我一直很困惑。因此,這裏是我的問題,我有這樣的文字:檢查標籤並使用PHP獲取標籤內的值

<ORGANIZATION>Head of Pekalongan Regency</ORGANIZATION>, Dra. Hj.. Siti Qomariyah , MA and her staff were greeted by <ORGANIZATION>Rector of IPB</ORGANIZATION> Prof. Dr. Ir. H. Herry Suhardiyanto , M.Sc. and <ORGANIZATION>officials of IPB</ORGANIZATION> in the guest room. 

我嘗試使用我的代碼進去<ORGANIZATION>標籤值:

function get_text_between_tags($string, $tagname) { 
    $pattern = "/<$tagname ?.*>(.*)<\/$tagname>/"; 
    preg_match($pattern, $string, $matches); 
    if(!empty($matches[1])) 
     return $matches[1]; 
} 

但這個代碼只檢索從一個值當有3個標籤<ORGANIZATION>時,最後一個標籤(officials of IPB)。

現在,我不知道要修改此代碼以獲取標籤內的所有值而不重複。所以請提前幫助,謝謝。 :D

+0

http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – 2013-05-09 03:58:00

+0

@MatthewGraves我不明白這篇文章(我的英語不好)。有沒有希望? – andrefadila 2013-05-09 04:03:44

+0

爲什麼我得到的投票下來:( – andrefadila 2013-05-09 04:41:28

回答

1

preg_match將只返回第一場比賽,而當前的代碼將失敗:

  • 變量沒有以同樣的方式
  • 標籤的內容是大寫的在多條線上
  • 同一行上有多個標籤。

相反,試試這個:

function get_text_between_tags($string, $tagname) { 
    $pattern = "/<$tagname\b[^>]*>(.*?)<\/$tagname>/is"; 
    preg_match_all($pattern, $string, $matches); 
    if(!empty($matches[1])) 
     return $matches[1]; 
    return array(); 
} 

這是解析可接受的使用正則表達式的,因爲它是一個明確界定的情況下。但是請注意,如果出於某種原因在標籤的屬性值內有>,它將會失敗。

如果你希望避免the wrath of the pony,試試這個:

function get_text_between_tags($string, $tagname) { 
    $dom = new DOMDocument(); 
    $dom->loadHTML($string); 
    $tags = $dom->getElementsByTagName($tagname); 
    $out = array(); 
    $length = $tags->length; 
    for($i=0; $i<$length; $i++) $out[] = $tags->item($i)->nodeValue; 
    return $out; 
} 
+0

我試過了,但仍然沒有工作。它返回一個空的數組。:) – andrefadila 2013-05-09 04:34:48

+0

你試過這兩塊代碼? – 2013-05-09 04:37:50

+0

我很抱歉,我已經嘗試了第二個代碼。第一個代碼是工作。謝謝師父。 :) – andrefadila 2013-05-09 04:40:48

-2

您是否嘗試過strip_tags()功能?

<?php 

    $s = "<ORGANIZATION>Head of Pekalongan Regency</ORGANIZATION>, Dra. Hj.. Siti Qomariyah , MA and her staff were greeted by <ORGANIZATION>Rector of IPB</ORGANIZATION> Prof. Dr. Ir. H. Herry Suhardiyanto , M.Sc. and <ORGANIZATION>officials of IPB</ORGANIZATION> in the guest room."; 

    $r = strip_tags($s); 

    var_dump($r); 

?> 

demo