在php中替换\ n \ r \ n换行符

时间:2013-09-21 12:01:09

标签: php xml str-replace

我写了一小段php,它从xml提要中获取项目(在这种情况下为产品)。我使用simplexml_load_file将feed的各个部分分配给变量。

它运行良好,我将结果输出到csv文件。我遇到的问题是xml中的一些项目是html描述并且在其中包含换行符。这打破了csv,因为它将这些视为新行。

为了解决这个问题,我在csv的每一行添加了行尾字符串,我试图从描述中删除所有\ n \ r,然后用\ n替换eol字符串csv工作。

我可以用notepad ++手动完成它,但是当用php尝试它时它似乎无法工作。

以下是我尝试过的代码,但我可能已经搞砸了,因为我之前从未这样做过,而且它似乎没有用。生成的csv仍然具有原始换行符,并且eol字符串仍然存在。

//Get The Short and Long Descriptions from the $_item in the XML
   $short_Description = $_item->short_description;
   $description = $_item->description;

//OK now we need to firstly remove all the \n\r \n \r from the descriptions and once that's done replace "FEOL," with \n. Easy!

// Lets strip the LF and CR from the descriptions   
    $new_Line = array('\n\r', '\n', '\r');
    $replace = '';

    $short_Description = str_replace($new_Line, $replace, $short_Description);
    $description = str_replace($new_Line, $replace, $description);

// OK now we have one big long line lets add the CR or maybe LF back at the end of each line where we've put the FEOL place holder
    $eol   = 'FEOL,';
    $replace = '\r';

    $short_Description = str_replace($eol, $replace, $short_Description);
    $description = str_replace($eol, $replace, $description);

只是想知道他们是否有任何明显的遗漏,或者说我错了。 任何帮助将不胜感激。 佰

2 个答案:

答案 0 :(得分:1)

您正在替换“斜线n”和“斜杠r”而不是LF和CR字符:

$new_Line = array('\n\r', '\n', '\r');

使用双引号:

$new_Line = array("\n\r", "\n", "\r");

你可以自己看出差异:

<?php
print '\n';

将打印:\ n

虽然

<?php
print "\n";

将打印换行符

你确定它应该是“\ n \ r”而不是“\ r \ n”吗?

答案 1 :(得分:0)

这是PHP文档站点的一个示例:

http://php.net/manual/en/function.str-replace.php

$str     = "Line 1\nLine 2\rLine 3\r\nLine 4\n";
$order   = array("\r\n", "\n", "\r");
$replace = '';

$newstr = str_replace($order, $replace, $str);

正如您所看到的,您应该在每个数组项周围使用双引号,并且应该像您一直在替换\r\n而不是\n\r

相关问题