开发者

Removing newlines in php

Following is the syntax for preg_rep开发者_开发百科lace() function in php:

$new_string = preg_replace($pattern_to_match, $replacement_string, $original_string);

if a text file has both Windows (rn) and Linux(n) End of line (EOL) characters i.e line feeds.

then which of the following is the correct order of applying preg_replace() to get rid of all end of line characters?

  1. remove cr first

    $string = preg_replace('|rn|','',$string);
    $string = preg_replace('|n|','',$string);
    
  2. remove plain nl first

    $string = preg_replace('|n|','',$string);
    $string = preg_replace('|rn|','',$string);
    


I would recommend to use: (Windows, Unix and Mac EOL characters)

$string = preg_replace('/\r|\n/m','',$string);

Notice m multiline modifier.


which of the following is the correct order of applying preg_replace to get rid of all end of line characters?

$string = preg_replace("!\r|\n!m",'',$string);


Using the power of regular expressions, you could specify something like

'|[\r][\n]|'

which specifically mean, 0 or 1 '\r', then 0 or 1 '\n' which would match the end of a row under both linux and windows.

EDIT: Using the build-in function trim would achieve the same result in an even better manner, but only if the newline characters are located at the beginning or end of the string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜