Problem Replacing Literal String \r\n With Line Break in PHP

◇◆丶佛笑我妖孽 提交于 2020-01-15 08:01:08

问题


I have a text file that has the literal string \r\n in it. I want to replace this with an actual line break (\n).

I know that the regex /\\r\\n/ should match it (I have tested it in Reggy), but I cannot get it to work in PHP.

I have tried the following variations:

preg_replace("/\\\\r\\\\n/", "\n", $line);

preg_replace("/\\\\[r]\\\\[n]/", "\n", $line);

preg_replace("/[\\\\][r][\\\\][n]/", "\n", $line);

preg_replace("/[\\\\]r[\\\\]n/", "\n", $line);

If I just try to replace the backslash, it works properly. As soon as I add an r, it finds no matches.

The file I am reading is encoded as UTF-16.

Edit:

I have also already tried using str_replace().

I now believe that the problem here is the character encoding of the file. I tried the following, and it did work:

$testString = "\\r\\n";
echo preg_replace("/\\\\r\\\\n/", "\n", $testString);

but it does not work on lines I am reading in from my file.


回答1:


UTF-16 is the problem. If you're just working with raw the bytes, then you can use the full sequences for replacing:

$out = str_replace("\x00\x5c\x00\x72\x00\x5c\x00\x6e", "\x00\x0a", $in);

This assumes big-endian UTF-16, else swap the zero bytes to come after the non zeros:

$out = str_replace("\x5c\x00\x72\x00\x5c\x00\x6e\x00", "\x0a\x00", $in);

If that doesn't work, please post a byte-dump of your input file so we can see what it actually contains.




回答2:


Save yourself the effort of figuring out the regex and try str_replace() instead:

str_replace('\r\n', "\n", $string);



回答3:


Save yourself the effort of figuring out the regex and the escaping within double quotes:

$fixed = str_replace('\r\n', "\n", $line);

For what it is worth, preg_replace("/\\\\r\\\\n/", "\n", $line); should be fine. As a demonstration:

var_dump(preg_replace("/\\\\r\\\\n/", "NL", 'Cake is yummy\r\n\r\n'));

Gives: string(17) "Cake is yummyNLNL"

Also fine is: '/\\\r\\\n/' and '/\\\\r\\\\n/'

Important - if the above doesn't work, are you even sure literal \r\n is what you're trying to match?..




回答4:


$result = preg_replace('/\\\\r\\\\n/i', '\n', $subject);


来源:https://stackoverflow.com/questions/7098488/problem-replacing-literal-string-r-n-with-line-break-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!