'Obtain first line of a string in PHP

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?



Solution 1:[1]

It's late but you could use explode.

<?php
$lines=explode("\n", $string);
echo $lines['0'];
?>

Solution 2:[2]

$first_line = substr($fulltext, 0, strpos($fulltext, "\n"));

or something thereabouts would do the trick. Ugly, but workable.

Solution 3:[3]

try

substr( input, 0, strpos( input, "\n" ) )

Solution 4:[4]

echo str_replace(strstr($input, '\n'),'',$input);

Solution 5:[5]

list($line_1, $remaining) = explode("\n", $input, 2);

Makes it easy to get the top line and the content left behind if you wanted to repeat the operation. Otherwise use substr as suggested.

Solution 6:[6]

not dependent from type of linebreak symbol.

(($pos=strpos($text,"\n"))!==false) || ($pos=strpos($text,"\r"));

$firstline = substr($text,0,(int)$pos);

$firstline now contain first line from text or empty string, if no break symbols found (or break symbol is a first symbol in text).

Solution 7:[7]

try this:

substr($text, 0, strpos($text, chr(10)))

Solution 8:[8]

You can use strpos combined with substr. First you find the position where the character is located and then you return that part of the string.

$pos = strpos(input, "\n");

if ($pos !== false) {
echo substr($input, 0, $pos);
} else {
echo 'String not found';
}

Is this what you want ?

l.e. Didn't notice the one line restriction, so this is not applicable the way it is. You can combine the two functions in just one line as others suggested or you can create a custom function that will be called in one line of code, as wanted. Your choice.

Solution 9:[9]

Many times string manipulation will face vars that start with a blank line, so don't forget to evaluate if you really want consider white lines at first and end of string, or trim it. Also, to avoid OS mistakes, use PHP_EOL used to find the newline character in a cross-platform-compatible way (When do I use the PHP constant "PHP_EOL"?).

$lines = explode(PHP_EOL, trim($string));
echo $lines[0];

Solution 10:[10]

A quick way to get first n lines of a string, as a string, while keeping the line breaks.

Example 6 first lines of $multilinetxt

echo join("\n",array_splice(explode("\n", $multilinetxt),0,6));

Can be quickly adapted to catch a particular block of text, example from line 10 to 13:

echo join("\n",array_splice(explode("\n", $multilinetxt),9,12)); 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Connor Gurney
Solution 2 Marc B
Solution 3 Sirko
Solution 4 Krimo
Solution 5 Your Common Sense
Solution 6 Alexander C
Solution 7 mignz
Solution 8
Solution 9 Benjamin
Solution 10 NVRM