删除PHP中的换行符和换行符

Removing Line Breaks and Newlines in PHP

本文关键字:换行符 PHP 删除      更新时间:2023-09-26

CKEditor正在我的数据库中输入的内容中添加新行,这很好,只是这些数据需要作为一行html呈现到javascript中。

在我的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>'

我如何在不删除字符之间的正常间距的情况下写出所有这些新行?

我认为这是因为您在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>

这就成功了:

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

能够去除所有的剩余部分,现在呈现得很完美。