2012-09-07 32 views
0

我使用preg_mach用於提取一些HTML(我嘗試使用DOM文檔,但我有一些問題,新行) 任何方式......這是我的代碼..提取與一些的preg_match HTML

1.HTML

<body> 


      <!-- icon and title --> 
      <div class="smallfont"> 
       <img class="inlineimg" src="images/icons/icon1.gif" alt="" border="0" /> 
       <strong>qrtoobah 3nwan</strong> 
      </div> 
      <hr size="1" style="color:#CCCCCC; background-color:#CCCCCC" /> 
      <!--/icon and title --> 


     <div id="post_message_14142536"> 

      <font size="7"><font color="red">msaha 700</font></font><br /> 
<font size="7"><font color="red">shamali 20</font></font><br /> 
<font size="7"><font color="red"> 1700 almetr</font></font><br /> 
<font size="7"><font color="#ff0000">sooom bs</font></font><br /> 
<font size="7"><font color="#ff0000">albee3 qreeb</font></font> 
     </div> 
     <!-- message --> 


</body> 

extract.php

<?php 
$html = file_get_contents("1.html"); 
$pattern = '/<([!]+)([^]+).*>([^]+)(message\ \-\-\>)/'; 
    preg_match($pattern, $html, $matches); 
print_r($matches); 


?> 

我想<!-- icon and title -->)blablabla(<!--/message -->之間的任何東西...... ,但我得到這個數組:

Array ([0] => [1] => ! [2] => -- [3] => message -->) 
+0

我認爲這個問題更加微不足道。右鍵單擊 - >查看源代碼。 'Array([0]'是什麼都不是,因爲它是一個html註釋,因此不會顯示。 – MarcDefiant

+0

您還需要通過「s」或「m」(不知道哪個)修飾符才能使'.'匹配換行 – MarcDefiant

+0

有沒有什麼辦法提取它..或提取上面的兩個div – aboji

回答

0

使用strpos找到第一個標記位置。然後用strpos找到結束標籤。我的意思是 - 如果你知道你從哪裏尋找什麼,並且它們是獨一無二的......那麼preg_*函數中有什麼關係呢?

所以我想這樣的事情會正常工作(我使代碼清楚地理解我在一步一步的行動想法):

$tag_begin = "<!-- icon and title -->"; 
$tag_end = "<!-- message -->"; 
$begin  = strpos($tag_begin,$text)+strlen($tag_begin); 
$end  = strpos($tag_end,$text); 
$result = substr($begin,$end, $text); 


也ü可以做完全相同,如果你想找到並存儲開放<!-- (.*) -->和關閉<!--/(.*) -->之間的所有結構。
只有你必須改變 - 首先用preg_match找到所有打開的結構名稱。例如:

$result_cnt = preg_match_all('#<!-- [^/].*-->#', $text , $openings); 

// Output for your example HTML is: 
$openings = 
array (
    0 => 
    array (
    0 => '<!-- icon and title -->', 
    1 => '<!-- message -->', 
), 
) 

之後,單循環$開頭和找到所有需要的代碼。只需在合適的位置加入關閉「/」字樣的開口即可。