php 计算已发布字符串中的行数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7955402/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:40:55  来源:igfitidea点击:

Count lines in a posted string

phpcountlines

提问by Cyclone

I've tried this: count new lines in textarea to resize container in PHP?

我试过这个:计算 textarea 中的新行以调整 PHP 中的容器大小?

But it doesn't seems to be working:

但它似乎不起作用:

$content = nl2br($_POST['text']);
preg_match_all("/(<br>)/", $content, $matches);

echo count($matches[0]) + 1;

It'll always output 1.

它总是会输出1.

Is there any other solutions to count lines in a string?

有没有其他解决方案来计算字符串中的行数?

回答by K2xL

Found this in one of my old apps... Not sure where I got it from.

在我的一个旧应用程序中找到了这个……不知道我从哪里得到的。

$lines_arr = preg_split('/\n|\r/',$str);
$num_newlines = count($lines_arr); 
echo $num_newlines;

*Edit - Actually, this probably won't work if your textarea is spitting out html.. check for <br> and <br/>

*编辑 - 实际上,如果您的 textarea 吐出 html,这可能不起作用.. 检查 <br> and <br/>

回答by Pastushenko Yuri

You can try this:

你可以试试这个:

$count = substr_count($_POST['text'], "\n") + 1;

or:

或者:

$count = count(explode("\n", $_POST['text']));

回答by yckart

count( explode(PHP_EOL, $str) );