【问题标题】:Removing Line Breaks and Newlines in PHP在 PHP 中删除换行符和换行符
【发布时间】:2013-11-21 04:22:41
【问题描述】:

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

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

【问题讨论】:

  • 为什么不编写一个简单的正则表达式来删除行尾/空格/行尾等序列?
  • 尝试使用 nl2br()。 php.net/manual/en/function.nl2br.php
  • 我也尝试过$tmpmaptext = preg_replace('/\s+/', '', $tmpmaptext);,但删除所有间距太过分了。我不知道删除新行的正则表达式,否则我会尝试。
  • @VinceKronlein \n 是换行符,\r 是回车符。将字符放在方括号中以匹配集合中的任何字符。此外,您可能希望将其替换为单个换行符,而不是空字符串。

标签: javascript php regex


【解决方案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>

【讨论】:

  • 另外,如果将搜索数组中的“\t”替换为“”(4个空格),就会消除大的空白。
【解决方案2】:

这成功了:

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

能够移除所有其余部分,并且现在可以完美呈现。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多