2016-03-19 181 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