2013-11-21 63 views
0

CKEditor在我的數據庫中輸入的內容中添加了新行,這很好,除了需要將這些數據以javascript形式呈現爲一行html。在PHP中刪除換行符和換行符

在我的PHP我有:

$tmpmaptext = $map['maptext'][$this->config->get('config_language_id')]; 
$tmpmaptext = html_entity_decode($tmpmaptext, ENT_QUOTES, 'UTF-8'); 
$tmpmaptext = str_replace(array('\r\n', '\n', '\r', '\t'), '', $tmpmaptext); 
$tmpmaptext = str_replace(PHP_EOL, '', $tmpmaptext); 

這是幾乎所有我能找到的關於如何去除新線,但我的頁面,這仍然結束了:

var infowindow01 = new google.maps.InfoWindow({ 
     content: '<div><h2>Title</h2> 

<p>Address line 1,<br /> 
Address line 2</p> 

<p>phone number</p> 

<p><a href="http://www.example.com" target="_blank">www.example.com</a></p> 
</div>' 

如何在不刪除字符之間的正常間距的情況下將所有這些新行取出?

+0

爲什麼不寫一個簡單的正則表達式來刪除像線結束/空白/行結束的序列? –

+0

嘗試使用nl2br()。 http://php.net/manual/en/function.nl2br.php – Ali

+0

我也嘗試過'$ tmpmaptext = preg_replace('/ \ s + /','',$ tmpmaptext);'但是這太過於刪除所有間距。我不知道刪除新行的正則表達式,或者我會嘗試。 –

回答

1

我認爲這是因爲你正在str_replace中使用單引號,它將搜索字符串'\ n'(斜槓n)。如果使用雙引號,將\ n轉換爲換行符...

$maptext = '<div><h2>Title</h2> 

<p>Address line 1,<br /> 
Address line 2</p> 

<p>phone number</p> 

<p><a href="http://www.example.com" target="_blank">www.example.com</a></p> 
</div>'; 

$no_newlines = str_replace(array("\n", "\r\n", "\r", "\t", " "), "", $maptext); 

echo($no_newlines); 

輸出:

<div><h2>Title</h2><p>Address line 1,<br />Address line 2</p><p>phone number</p><p><a href="http://www.example.com" target="_blank">www.example.com</a></p></div> 
+0

此外,如果在搜索數組中使用「」(4個空格)替換「\ t」,它將消除很大的差距。 – MikeJerome

0

這奏效了:

$tmpmaptext = $map['maptext'][$this->config->get('config_language_id')]; 
$tmpmaptext = preg_replace('/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/', '', $tmpmaptext); 

之所以能夠去除所有其餘的,現在完美渲染。