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?
remove cr first
$string = preg_replace('|rn|','',$string); $string = preg_replace('|n|','',$string);
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.
精彩评论