60

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.

rsk82
  • 28,217
  • 50
  • 150
  • 240
  • 1
    You might find [`s($str)->normalizeLineEndings()->count("\n")`](https://github.com/delight-im/PHP-Str/blob/ea3e40132e9d4ce27da337dae6286f2478b15f56/src/Str.php#L669) helpful, as found in [this standalone library](https://github.com/delight-im/PHP-Str). This does two things: First, it normalizes all kinds of newlines (LF, CR, CRLF and Unicode newlines) to LF. Then it counts the LFs in a multibyte-safe way. – caw Jul 28 '16 at 04:14

4 Answers4

111

substr_count should do the trick:

substr_count( $your_string, "\n" );
George Cummins
  • 28,485
  • 8
  • 71
  • 90
  • 2
    Thoughts about using PHP_EOL? I've been using the constant, and was curious about if I can just use \n, as you've outlined, instead. Thanks for your thoughts! – Bob Gregor Sep 13 '13 at 14:48
  • @BobGregor This question asked specifically for a way to find "\n" but there is certainly nothing wrong with using PHP_EOL if you are looking for a way to find the end-of-line string in a cross-platform manner. – George Cummins Sep 14 '13 at 00:24
  • 5
    Note that double quotes `"` around `\n` are required: `substr_count( $your_string, "\n" );` works while `substr_count( $your_string, '\n' );` doesn't. – Brendan Nee Jul 05 '15 at 00:37
8

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

Hoàng Vũ Tgtt
  • 1,863
  • 24
  • 8
7

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.

Carlos Precioso
  • 2,731
  • 3
  • 21
  • 24
2
$count=preg_match_all ('/\n/',$str);
Trey
  • 5,480
  • 4
  • 23
  • 30