In PHP 5.3 there is a nice function that seems to do what I want:
strstr(input,"\n",true)
Unfortunately, the server runs PHP 5.2.17 and the optional third parameter of strstr
is not available. Is there a way to achieve this in previous versions in one line?
$str = strtok($input, "\n"); that will return the first non-empty line from the text in the unix format.
If you ABSOLUTELY know the file exists, you can use a one-liner: $line = fgets(fopen($file, 'r')); The reason is that PHP implements RAII for resources. That means that when the file handle goes out of scope (which happens immediately after the call to fgets in this case), it will be closed.
\r is a Carriage Return \n is a Line Feed (or new line). On Windows systems these together make a newline (i.e. every time you press the enter button your fix will get a \r\n ). In PHP if you open a Windows style text file you will get \r\n at the end of paragraphs / lines were you've hit enter.
Given that a line could be delimited by either one ("\n") or two ("\r\n") characters, the most bullet-proof method would be
$line = preg_split('#\r?\n#', $input, 0)[0];
for any sequence before the first line feed, even if it an empty string, and
$line = preg_split('#\r?\n#', ltrim($input), 0)[0];
for the first non-empty string.
When this answer was first written, almost a decade ago, it featured a few subtle nuances
PHP_EOL
is not the solution as we can be dealing with outside data, not affected by the local system settingsexplode()
or preg_split()
in one line, hence a trick with strtok()
was proposed. However, shortly after, thanks to the Uniform Variable Syntax, proposed by Nikita Popov, it become possible to use one of these functions in a neat one-linerbut as this question gained some popularity, it is essential to cover all the possible edge cases in the answer. But for the historical reasons here is the original answer
$str = strtok($input, "\n");
that will return the first non-empty line from the text in the unix format.
However, given that the line delimiters could be different and the behavior of strtok()
is not that straight, as "Delimiter characters at the start or end of the string are ignored", as it says the man page for the original strtok() function in C, now I would advise to use this function with caution.
It's late but you could use explode.
<?php $lines=explode("\n", $string); echo $lines['0']; ?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With