简体   繁体   English

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

[英]Removing Line Breaks and Newlines in PHP

CKEditor is adding new lines in my content that's entered into my database, which is fine, except that this data needs to be rendered to javascript as a single line of html. CKEditor会在我输入到数据库中的内容中添加新行,这很好,只是该数据需要作为html的一行呈现给javascript。

In my PHP I have: 在我的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);

Which is pretty much everything I can find on how to remove new lines but I'm still ending up with this in the page: 在删除新行方面,我几乎可以找到所有这些内容,但是我仍然在页面中结束了这一点:

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>'

How can I get all these new lines out without removing that normal spacing between characters? 如何在不删除字符之间的正常间距的情况下取出所有这些新行?

I think it's because you're using single-quotes in str_replace which will search for the string '\\n' (slash n). 我认为这是因为您在str_replace中使用单引号将搜索字符串'\\ n'(斜线n)。 If you use double-quotes it will convert \\n to the newline character... 如果您使用双引号将\\ 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);

outputs: 输出:

<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>

This did the trick: 这达到了目的:

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

Was able to remove all the rest and it renders perfectly now. 能够删除所有其余部分,并且现在可以完美呈现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM