I have the following function to get all of the different types of end-of-line delimiters in a file. There may be one or more, so I want to return an array of all types.
function ddtt_get_file_eol( $file_contents, $incl_code = true ) {
$types = [
'rn',
'n',
'r'
];
$found = [];
foreach ( $types as $type ) {
if ( $type == 'rn' ) {
$regex = "/rn/";
} elseif ( $type == 'n' ) {
$regex = "/(?<!r)n/";
} else {
$regex = "/r(?!n)/";
}
if ( preg_match( $regex, $file_contents ) ) {
$found[] = ( $incl_code ) ? '<code class="hl">'.$type.'</code>' : $type;
}
}
return $found;
} // End ddtt_get_php_eol()
The problem I am having is that it is recognizing rn
as two separate types and outputting [ 'n', 'r' ]
. I want to output [ 'rn' ]
if it is just using that type, or [ 'rn', 'n' ]
if using both types, etc. How do I modify my code to correctly fetch all types used?
2
Answers
In my opinion, your code is fine. It’s just your input which is a mixture.
Outputs the following:
which seems completely normal.
You can test/play with it here: https://onlinephp.io/c/4ce47
Let me guess, you are a developer who wants perfect identification of newline sequences regardless of the environment AND you want to keep all of your hair?
PHP has had a solution for this for a long time and it doesn’t involve Minoxidil; just use
R
. I’ll replace each newline sequence with an asterisk to show how it reliably respects all possible newline sequences across all environments and treats them as whole newline sequences whenever appropriate.Code: (Demo)
Output:
Relevant reading on implementations of
R
: