2016-03-19 177 views
1

我正在使用以下代碼刪除html中的空白。我只想刪除兩個標籤之間的空格。但是,下面的代碼替換所有空格刪除HTML中標記之間的空白空間

即刪除「>」和之間的所有空格「<」

//read the entire string 
$str=file_get_contents('sample.txt'); 

//replace all white spaces 
$str=str_replace("\n", "",$str); 
$str=str_replace("\t", "",$str); 
$str=str_replace(" ", "",$str); 

//write the entire string 
file_put_contents('sample.txt', $str); 
+3

你可以使用'DomDocument'與['preserveWhiteSpace = FALSE'](http://php.net/manual/en/class.domdocument.php#domdocument .props.preservewhitespace)另外一個問題[在這裏](http://stackoverflow.com/questions/7997936/how-do-you-format-dom-structures-in-php)。 – Jan

+0

你也可以使用整理 –

+0

因爲你沒有說明你的目的 - 爲什麼你想刪除空白,並在什麼階段很難推薦某些具體的東西雖然[正則表達式不是一個好方法](http: //stackoverflow.com/q/1732348/17300)。正如丹尼爾所說,我已經使用tidy/jTiey。 –

回答

4

您需要使用正規表示法。

也許你可以使用這個:

$html = preg_replace('/(\>)\s*(\<)/m', '$1$2', $html); 
+0

儘管該代碼可能會在一個緊湊的工作,這種方法通常不安全;請參閱https://stackoverflow.com/a/1732454/3159183 – SeldomNeedy