Search code examples
phptextfopenstrlen

Unreadable Characters in a String


This is the code which gets a text and do a process on every line:

<?php
$f = fopen('text.txt' , 'r');
$i = 0;
while($line = fgets($f)){
    if($i == 1){
        $first_line = $line;
    }elseif($i == 2){
        $second_line= $line;
    }elseif($i == 3){
        $third_line = $line;
    }
    $i++;
}
?>

The text.txt contains:

3
ABC
aBD

When I run below code, it gives me a strange output which is:

echo strlen($second_line);

$second_line should be ABC but the returned output is this:

5

Also urlencode($second_line) shows:

ABC%0D%0A

one of these 5 characters is "\n" that goes to next line

The main question is, what is the another one hidden character?


Solution

  • As Windows uses \r\n as the line termination, this will add an extra 2 chars to each string. Linux only uses \r so this is just 1 extra.

    To provide a generic solution, it would be better to use

    $line = trim($line);
    

    which will remove any line termination characters. It will also remove leading and trailing spaces.