php 如何计算一个非常大的字符串中的新行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6204759/
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
how to count new lines in a very big string?
提问by rsk82
The problem reduces to counting \n
characters, so is there a function that can do it on a huge strings, since explode() wastes too much memory.
问题归结为计数\n
字符,因此是否有一个函数可以在巨大的字符串上执行此操作,因为explode() 浪费了太多内存。
回答by George Cummins
回答by Carlos Precioso
You can use PHP's substr_count()
function: http://www.php.net/manual/en/function.substr-count.php
你可以使用PHP的substr_count()
功能:http: //www.php.net/manual/en/function.substr-count.php
substr_count($myString, "\n");
substr_count($myString, "\n");
It will give you an integer with the number of occurrences.
它会给你一个带有出现次数的整数。
回答by Hoàng V? Tgtt
i Think substr_count( $your_string, "\n" ); should be:
我认为 substr_count( $your_string, "\n" ); 应该:
$numLine = substr_count( $your_string, "\n" ) +1;
But I use this:
但我用这个:
$numLine = count(explode("\n",$your_string));
it always return correct result
它总是返回正确的结果
回答by Trey
$count=preg_match_all ('/\n/',$str);