tags:

views:

252

answers:

3

What would be the best way to detect newline return method in PHP. CR, LF or CR+LF

And if possible convert it to specified type.

A: 

This will test a string for a newline character (CR or LF):

function has_newline($string)
{
    return (strpos($string, "\r") !== false || strpos($string, "\n") !== false);
}

(\r means CR and \n means LF)

You can use the same thinking to convert them. For example, this function converts all CRs to LFs in a given string:

function replace_returns($string)
{
    return str_replace("\r", "\n", $string);
}
Josh Leitzel
i reckon replace_returns($string) you wrote works nicely on cross-platform. imagine \r\n (single newline in Windows), it will be converted to \n\n (2 new lines in *nux!)
thephpdeveloper
I understand your point, but my purpose wasn't to imagine every circumstance for the OP, it was to point him in the right direction.
Josh Leitzel
+2  A: 
define('NL_NIX', "\n"); // \n only
define('NL_WIN', "\r\n"); // \r\n
define('NL_MAC', "\r");  // \r only


function newline_type($string){

  if(strpos($string,NL_WIN)!==false){
    return NL_WIN;
  }elseif(strpos($string,NL_MAC)!==false){
    return NL_MAC;
  }elseif(strpos($string,NL_NIX)!==false){
    return NL_NIX;
  }

}

Checks what kind of newline is in the string. 0 is returned when no newline is found.

To normalize/standardize all newlines use the following function:

function newline_convert($string, $nl){
  return str_replace(array(NL_WIN, NL_MAC, NL_NIX), $nl, $string);
}

Hope it helps!

thephpdeveloper
I like the idea of your functions, but they're a little verbose. In newline_type, why not just `return` after every `if` instead of storing it as `$result`? Then just `return 0;` at the end. No need for the variable. With `newline_convert`, why not just `return str_replace...`?
Josh Leitzel
@Josh - it is good practice to split up the code. easier for debugging or what. I'm used to it because I learnt my lesson - finding out what went wrong and so on. it's fine if you combine them into a single line too.
thephpdeveloper
But there's a difference between 'good practice' and being unnecessarily verbose. For instance, in your first function you create an entirely new variable just to store something you don't need to store. And I fail to see how (in this instance) it makes anything clearer; if anything it just makes things more complex. Just some food for thought. ;)
Josh Leitzel
thephpdeveloper
+1  A: 

The constant PHP_EOL contains the platform specific newline character.

troelskn