2013-06-28 29 views
0

上面的代碼工作確定:PHP - 使用的preg_replace用的file_get_contents

<?php 

function clearPage($content, $class) { 
$arr = array(
      '@^(.*?)<div class="'.$class.'">(.*?)</div>(.*?)[email protected]' => '<div class="'.$class.'">$2</div>' 
      ); 

    return preg_replace(array_keys($arr), array_values($arr), $content); 


} 


$class = "something"; 
$content = "31xu1823y8<div class="something">Wanted</div>912u38u3" 
$result = clearPage($content, $class); 
echo $result; 
?> 

此輸出:

<div class="something">Wanted</div> 

但我想使變量的內容,是從網站頁面的HTML代碼。因此,我將最後一個代碼更改爲如下所示:

$class = "something"; 
$content = file_get_contents('index.php'); 
$result = clearPage($content, $class); 
echo $result; 

This outputs all the webpage! Why!? 
+0

我猜你會發現在這太問題的答案 - > HTTP:/ /stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – adeneo

+0

是的,如果你從'input.php'中讀取,你將不會呈現HTML,但PHP只有HTML片段的源代碼。 (正則表達式問題:DOTALL標誌。) – mario

回答

0

使用正則表達式或字符串匹配是解析HTML的最糟糕方式。

您需要使用DOM: http://php.net/manual/en/book.dom.php

或第三方DOM庫,像這樣: http://simplehtmldom.sourceforge.net/

+0

爲什麼不用類似的非特定答案關閉數以百計的類似問題之一? – mario

+0

我認爲我的解決方案是好的,但問題是,我認爲我沒有從頁面獲取html代碼,所以它不能取代任何東西。 –