PHP 获取字符串的第一行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9097682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Obtain first line of a string in PHP
提问by kinokijuf
In PHP 5.3 there is a nice functionthat seems to do what I want:
在 PHP 5.3 中有一个很好的函数,它似乎可以做我想做的事:
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?
不幸的是,服务器运行 PHP 5.2.17 并且可选的第三个参数strstr
不可用。有没有办法在一行中在以前的版本中实现这一点?
回答by Your Common Sense
回答by Connor Gurney
It's late but you could use explode.
已经晚了,但你可以使用爆炸。
<?php
$lines=explode("\n", $string);
echo $lines['0'];
?>
回答by Marc B
$first_line = substr($fulltext, 0, strpos($fulltext, "\n"));
or something thereabouts would do the trick. Ugly, but workable.
或有关的东西可以解决问题。丑陋,但可行。
回答by Sirko
try
尝试
substr( input, 0, strpos( input, "\n" ) )
回答by Krimo
echo str_replace(strstr($input, '\n'),'',$input);
echo str_replace(strstr($input, '\n'),'',$input);
回答by Paul Norman
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.
如果您想重复操作,可以轻松获得顶行和留下的内容。否则按照建议使用 substr。
回答by Andrés Torres
try this:
尝试这个:
substr($text, 0, strpos($text, chr(10))
回答by Alexander C
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).
$firstline 现在包含文本或空字符串的第一行,如果没有找到中断符号(或中断符号是文本中的第一个符号)。
回答by Benjamin
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"?).
很多时候字符串操作会面临以空行开头的变量,所以不要忘记评估是否真的要在字符串的开头和结尾考虑白线,或者修剪它。此外,为了避免操作系统错误,请使用 PHP_EOL 用于以跨平台兼容的方式查找换行符(何时使用 PHP 常量“PHP_EOL”?)。
$lines = explode(PHP_EOL, trim($string));
echo $lines[0];
回答by NVRM
A quick way to get first n lines of a string, as a string, while keeping the line breaks.
一种快速获取字符串的前 n 行的方法,作为字符串,同时保留换行符。
Example 6 first lines of $multilinetxt
示例 6 $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:
可以快速适应以捕获特定的文本块,例如第 10 到 13 行:
echo join("\n",array_splice(explode("\n", $multilinetxt),9,12));