Php replace line endings

Convert ending line of a file with a php script

Thank you. Solution 1: New lines are saved automatically as new lines in mysql, there is no need to do anything special for that. It’s probably \n because when u dump it it return text line by line like when you use Question:

Convert ending line of a file with a php script

I’d like to know if it’s possible to convert the endings lines mac (CR : \r) to windows (CRLF : \r\n) with a php script.

Indeed I’ve got a php script which run periodically on my computer to upload some files on a FTP server and the ending lines need to be changed before the upload. It’s easy to do it manually but I would like to do it automatically.

Can you just use a simple regular expression like the following?

function normalize_line_endings($string) < return preg_replace("/(?<=[^\r]|^)\n/", "\r\n", $string); >

It’s probably not the most elegant or fastest solution but it should work pretty well (i.e it won’t mess up existing Windows (CRLF) line-endings in a string).

Explanation

Basically load the file to a string and call something like :

function normalize($s) < // Normalize line endings // Convert all line-endings to UNIX format $s = str_replace(array("\r", "\n"), "\r\n", $s); // Don't allow out-of-control blank lines $s = preg_replace("/\r\n/", "\r\n\r\n", $s); return $s; > 

This is a snippet from here, last regeg might need some further tinkering with.

Edit: Fixed logic to remove duplicate replacements.

In the end the safer way is to change what you don’t want replaced first, here my function :

/**Convert the ending-lines CR et LF in CRLF. * * @param string $filename Name of the file * @return boolean "true" if the conversion proceed without error and else "false". */ function normalize ($filename) < echo "Convert the ending-lines of $filename into CRLF ending-lines. "; //Load the content of the file into a string $file_contents = @file_get_contents($filename); if (!file_contents) < echo "Could not convert the ending-lines : impossible to load the file.PHP_EOL"; return false; >//Replace all the CRLF ending-lines by something uncommon $DontReplaceThisString = "\r\n"; $specialString = "!£#!Dont_wanna_replace_that!#£!"; $string = str_replace($DontReplaceThisString, $specialString, $file_contents); //Convert the CR ending-lines into CRLF ones file_contents = str_replace("\r", "\r\n", $file_contents); //Replace all the CRLF ending-lines by something uncommon $file_contents = str_replace($DontReplaceThisString, $specialString, $file_contents); //Convert the LF ending-lines into CRLF ones $file_contents = str_replace("\n", "\r\n", $file_contents); //Restore the CRLF ending-lines $file_contents = str_replace($specialString, $DontReplaceThisString, $file_contents); //Update the file contents file_put_contents($filename, $file_contents); echo "Ending-lines of the file converted.PHP_EOL"; return true; > 

I tested it but there’s some error : it seems that instead of replacing the CR ending-line it add a CRLF ending-line, here’s the function, i slightly modified it to avoid to open the file outside this function :

// FONCTION CONVERTISSANT LES FINS DE LIGNES CR TO CRLF function normalize ($filename) < echo "Convert the ending-lines of $filename. "; //Load the file into a string $string = @file_get_contents($filename); if (!string) < echo "Could not convert the ending-lines : impossible to load the file.\n"; return false; >//Convert all line-endings $string = str_replace(array("\r", "\n"), "\r\n", $string); // Don't allow out-of-control blank lines $string = preg_replace("/\r\n/", "\r\n", $string); file_put_contents($filename, $string); echo "Ending-lines converted.\n"; return true; > 

How to convert the line endings of a text file from DOS, Sorry if I’m making an obvious comment but almost all decent editors and IDEs allow you to choose the line feed style and change it on the fly. …

Line endings in a form textarea

When you post a form which has a textarea, what line endings are used? \r\n, \n or like local files does it depend on the OS?

I am tryring to find an RFC or W3C spec or something, or is it different based on OS/browser? Got a link?

and is it a standard or different based on browser/os. Proof?

I am not worried about the textarea content before it’s sent to the server, but the actual variable contents in PHP/server side.

This information can found in the HTML5 spec. It says that for the textarea element:

. there is the form submission value. It is normalized so that line breaks use U+000D CARRIAGE RETURN «CRLF» (U+000A) character pairs, and in addition, if necessary given the element’s wrap attribute, additional line breaks are inserted to wrap the text at the given width.

The element’s value is defined to be the element’s raw value with the following transformation applied:

Replace every occurrence of a «CR» (U+000D) character not followed by a «LF» (U+000A) character, and every occurrence of a «LF» (U+000A) character not preceded by a «CR» (U+000D) character, by a two-character string consisting of a U+000D CARRIAGE RETURN «CRLF» (U+000A) character pair.

If the element’s wrap attribute is in the Hard state, insert U+000D CARRIAGE RETURN «CRLF» (U+000A) character pairs into the string using a UA-defined algorithm so that each line has no more than character width characters. For the purposes of this requirement, lines are delimited by the start of the string, the end of the string, and U+000D CARRIAGE RETURN «CRLF» (U+000A) character pairs.

By HTML specs, a line break is represented as CR LF. In the default data format in form submission, it is represented encoded as %0D%0A . (This does not depend on the operating system and its native line ending conventions.) Your server-side code will take it from there. In PHP, you will see it as \r\n .

you will receive plain text — if u need to add
tags you can use http://php.net/manual/en/function.nl2br.php =)

I’m sorry if I didn’t understand to your question — don’t down vote me :\

EDIT: It’s probably \n because when u dump it it return text line by line like when you use echo «something\nsomething»;

How to remove line breaks (no characters!) from the, WARNING: This is an unreliable answer.PHP_EOL is defined differently on different systems. Sometimes it is a line feed, and other times it is …

How to save comment with paragraph(new line) and fetch it from database with paragraph?

In my site, I want user to write their comments. But when they push «enter» in textfield, I want to save this comment as new paragraph to mysql. And I want to fetch this comment from mysql with paragraph.

I googled it and many people suggest «nl2br()», but I couldn’t understand how I use it.How can I make it possible? Thank you.

New lines are saved automatically as new lines in mysql, there is no need to do anything special for that.

However, when you output new lines to html, they will show up as spaces (normally. ) so when you output to html you have to use nl2br() so that a
tag gets added with every new line.

Explode PHP string by new line, If user put new lines in Windows and the PHP is running on Linux the result may be broken. – barell. Use a solution that takes care of all the …

PHP: Remove line ending with ( and remove line starting with ) and grab second word of every line

I have a sample string as shown below. In the string, how can I remove line ending with ( and remove line starting with ) and grab second word of every line?

This is some text ( some more text, one line text, more and more text available, this one is even longer and even more text is available, ) this is the last line; This is also some more text ( Second time some more text, one line text second time , Once again more and more text available, finally this one is even longer and even more text is available, ) this is the last line; 

The string shown above comes from a text file. Can be either pasted in a textarea or a file could be uploaded and this text will be read from the file. So in the example shown above, expected output is:

some more text, one line text, more and more text available, this one is even longer and even more text is available, Second time some more text, one line text second time , Once again more and more text available, finally this one is even longer and even more text is available, //words are more line and one time line again this 

How to do the above in PHP?

You can use the explode , array_map , and array_filter functions to do what you want.

First you have to define functions to filter out the ( and ) lines, and to extract the second word of each line.

function filter_line($line) < //the regular expression detects a line ending with a ( or beginning with a ) if(preg_match('/(^\)|\($)/', trim($line))) return false; if(empty($line)) return false; return true; >function map_line($line) < //the regular expression here splits the line into pieces at any whitespace //in case they used multiple spaces or a tab $split = preg_split('/\s+/', trim($line)); //if there are one or zero words on this line then remove it from the result if(count($split) < 2) return false; //return the second word return $split[1]; >

Now that you have that, the rest is easy:

//this will split the whole text into an array of lines $array = explode("\n", $myTextGoesHere); //this will return an array of entries that are either the second word or false $filtered = array_filter($array, 'filter_line'); //at this point $filtered contains the first step. print_r($filtered); //finally, this will extract the second word from each line //and eliminate lines with less than two words $result = array_filter(array_map('map_line', $filtered)); //$result contains the output print_r($result); 

Incidentally, it’s clear you are trying to get type values from a CREATE TABLE statement — you might have to be a little more careful about how you parse that depending on your RDBMS.

//Assumes text is in $text //Some preparations $lines=explode("\n",$text); $output=array(); $words=array(); $recording=false; //Cycle lines foreach ($lines as $line) < //Empty lines: Keep if ($line=='') < $output[]=''; continue; >//Not recording: Wait for '(' if (!$recording) < if (substr($line,-1)=='(') $recording=true; continue; >//Recording: Ending? if (substr($line,0,1)==')') < $recording=false; continue; >//Recording: Keep line $output[]=$line; //Recording: Keep 2nd word $line=preg_split('/\s+/', trim($line)); if (sizeof($line)>1) $words[]=$line[1]; //Remove next line if you want to ignore 1-word lines else $words[]='--no-second-word--'; > 

Php — How to save comment with paragraph(new line), In my site, I want user to write their comments. But when they push «enter» in textfield, I want to save this comment as new paragraph to mysql. And I …

Источник

Replacing \r\n with PHP

Why was \r\n «automatically added»? I’d look into fixing that anomaly, rather than trying (in vain) to hack around it after-the-fact.

6 Answers 6

The main problem you have with all the variations you’ve tried is that both \n and \r are escape characters that are only escaped when you use them in a double-quoted string.

In PHP, there is a big difference between ‘\r\n’ and «\r\n» . Note the single-quotes in the first, and double-quotes in the second.

So: ‘\r\n’ will result in a four character string containing a slash, an ‘r’, another slash and an ‘n’, whereas «\r\n» will contain two characters, those being the new line and carriage return characters.

So the direct answer to your question is that you need to use the second of the examples you gave in the question, but with double quotes instead of single quotes:

It’s worth pointing out that this will remove all new lines from the input, and replace them with nothing. If there is more than one new line in the input, they will all be removed. Without knowing more about your application, I don’t know if this is what you want, but here are some thoughts:

  • If you only want to remove blank lines (and other white space) from the end of the input string, you can use the trim() function instead.
  • If you want to retain the formatting for output to HTML, then the nl2br() function will help you. If you want to output to HTML without the formatting, then you may not need to remove them, as the browser will not render line breaks from \n characters.
  • If you replace new lines with nothing, as per your example, the last word of the first line will now run directly into the first word of the second line, and so on. You may prefer to replace them with a space character rather than nothing.
  • It is possible that users may submit the input with only \n without the matching \r , or vice-versa (this may be due to their OS or browser, or a deliberate hack, or a number of other reasons). If you want to replace all instances of both these characters, a more reliable way to do it would be to replace them individually, rather than relying on them being next to one-another. str_replace() allows you to do this by specifying them in an array. You can also use strtr() or preg_replace() to achieve the same goal.

Источник

Читайте также:  Python print data type
Оцените статью