Obtain first line of a string in PHP

2019-03-10 16:01发布

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?

10条回答
甜甜的少女心
2楼-- · 2019-03-10 16:57

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.

查看更多
We Are One
3楼-- · 2019-03-10 17:01

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).

查看更多
爷的心禁止访问
4楼-- · 2019-03-10 17:02
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.

查看更多
Juvenile、少年°
5楼-- · 2019-03-10 17:07

here you go

$str = strtok($input, "\n");

strtok() Documentation

查看更多
登录 后发表回答