how to count new lines in a very big string?

PhpStringCount

Php Problem Overview


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.

Php Solutions


Solution 1 - Php

substr_count should do the trick:

substr_count( $your_string, "\n" );

Solution 2 - Php

You can use PHP's substr_count() function: http://www.php.net/manual/en/function.substr-count.php

substr_count($myString, "\n");

It will give you an integer with the number of occurrences.

Solution 3 - Php

i Think substr_count( $your_string, "\n" ); should be:

$numLine = substr_count( $your_string, "\n" ) +1;

But I use this:

$numLine = count(explode("\n",$your_string));

it always return correct result

Solution 4 - Php

$count=preg_match_all ('/\n/',$str);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionrsk82View Question on Stackoverflow
Solution 1 - PhpGeorge CumminsView Answer on Stackoverflow
Solution 2 - PhpCarlos PreciosoView Answer on Stackoverflow
Solution 3 - PhpHoàng Vũ TgttView Answer on Stackoverflow
Solution 4 - PhpTreyView Answer on Stackoverflow