2010-06-24 73 views
1

我正在解析出一個HTML表並根據行值構建一個數組。我的問題是返回的關聯鍵有一點空白在他們給我的最終結果是這樣的:關聯數組鍵中的空白PHP

Array ([Count ] => 6 [Class ] => 30c [Description] => Conformation Model (Combined 30,57)) 

所以這樣一行:

echo $myArray['Count']; 

echo $myArray['Count ']; 

給了我一個空白的結果。

現在我已經有了一個相當哈克工作四處走動......

foreach($myArray as $row){ 

    $count = 0; 
    foreach($row as $info){ 
     if($count == 0){ 
      echo 'Count:' . $info; 
      echo '<br>'; 
     } 
     if($count == 1){ 
      echo ' Class:' . $info; 
      echo '<br>'; 
     } 
     if($count == 2){ 
      echo ' Description:' . $info; 
      echo '<br>'; 
     } 
     $count++; 
    } 

}

我使用的解析,我發現here表功能:

function parseTable($html) 
{ 
    // Find the table 
    preg_match("/<table.*?>.*?<\/[\s]*table>/s", $html, $table_html); 

    // Get title for each row 
    preg_match_all("/<th.*?>(.*?)<\/[\s]*th>/", $table_html[0], $matches); 
    $row_headers = $matches[1]; 

    // Iterate each row 
    preg_match_all("/<tr.*?>(.*?)<\/[\s]*tr>/s", $table_html[0], $matches); 

    $table = array(); 

    foreach($matches[1] as $row_html) 
    { 
    preg_match_all("/<td.*?>(.*?)<\/[\s]*td>/", $row_html, $td_matches); 
    $row = array(); 
    for($i=0; $i<count($td_matches[1]); $i++) 
    { 
     $td = strip_tags(html_entity_decode($td_matches[1][$i])); 
     $row[$row_headers[$i]] = $td; 
    } 

    if(count($row) > 0) 
     $table[] = $row; 
    } 
    return $table; 
} 

我假設我可以通過更新正確的正則表達式來消除空白空間,但是,當然,我避免了像鼠疫這樣的正則表達式。有任何想法嗎?提前致謝。 -J

+1

任何具體的原因,爲什麼你不直接解析HTML使用這樣一個解析器? http://simplehtmldom.sourceforge.net/ – 2010-06-24 18:48:13

+0

我有一個非常具體的原因...從來沒有聽說過它直到現在;)感謝您指出它。 – 2010-06-24 18:52:34

回答

4

您可以使用trim除去開頭和結尾的空白字符:

$row[trim($row_headers[$i])] = $td; 

但不要用正則表達式解析HTML文檔;改用Simple HTML DOM ParserDOMDocument等合適的HTML解析器。

1

一個簡單的方法是改變

$row[$row_headers[$i]] = $td; 

到:

$row[trim($row_headers[$i])] = $td;