php – Counting the number lines in a string?

Counting the number lines in a string?

Solution:
it is very easy in php , you can explode that string with ‘\n’ that is used for new line

Example Code:

<?php
$string=”1\n2\n3\n”; // there are 3 lines in a string
$array= explode(“\n”, $string);
print “Total No. of lines are “.count($array)-1;
?>

8 Comments »

  1. Tam said

    Do you test with this? When I test, it output -1.
    Any problem?

    Plz mail to vo.mita.ov@gmail.com because I donot go here regularly. Thank you!

  2. datshay said

    it just outputs always 1….

  3. amitmondal said

    Nice tutorial….thanks for this post…..
    Please visit this link for learn more script.
    http://amitmondal.wordpress.com/

  4. RF said

    What if the string was a text blob from an SQL database. Is it possible to a number to each line for display in a textarea?

    • Glen Boonzaier said

      $string=”1\n2\n3\n”; // there are 3 lines in a string
      $array= explode(“\n”, trim($string));
      foreach($i=1;$i<=count($array);$i++){
      $array[$i] = "$i: " . $array[$i];
      }
      echo implode('\n',$array[$i]);

      • Glen Boonzaier said

        Apologies, change “foreach” to “for”

  5. Glen Boonzaier said

    Here is a better version:

    $string=”1\n2\n3\n”; // there are 3 lines in a string
    $array= explode(“\n”, trim($string));
    print “Total No. of lines are “.count($array);

    This will eliminate any whitespace trailers including new lines.

  6. Rishi said

    $string=”
    1
    3
    “;
    $array= explode(‘
    ‘, $string);
    echo “Total No. of lines are “.count($array);

RSS feed for comments on this post · TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: