Count lines with PHP and JS

1

I need a function that helps me to record a line break variable and, later using java script , display the line number in real time.

I would basically number the line being that I have to use PHP to receive and java script just to display in real time.

    
asked by anonymous 03.04.2014 / 00:45

2 answers

2

Javascript:

//Simplifiquei o JS, baseado na versão do @vmartins, muito mais enxuta
document.getElementById('texto').onkeyup = function() {
   count = this.value.split("\n").length;
   document.getElementById('contador').innerHTML = count;
   document.getElementById('linhas').value = count;
}

HTML:

<form action="" method="post">
   <textarea id="texto" name="texto" onKeyup="updateLineCount()" rows="10"></textarea><br>
   <input type="hidden" id="linhas" name="linhas" value="0">
   Linhas: <span id="contador"></span>
</form>

See demo on SQL Fiddle

  

Note: row count will be sent in a hidden field , to answer the question, however, it is best to retell via PHP, and not send the value as it can be modified manually and / or simulated.

PHP:

(we are not using the hidden HTML field, but rather "retelling" via PHP)

<?php
   $texto = $_POST('texto');
   $linhas = explode("\n", $texto);
   $conta = count($linhas);
   //... se for mostrar as linhas individualmente,
   //    pode iterar a array $linhas aqui ...
   echo $conta;
?>
    
18.04.2014 / 03:51
0

To get the full rows of a textarea in javascript, you can do something like:

seu_textarea.value.split('\n').length

Example: link

In PHP, you can use the substr_count () function to count the total break of lines in a string.

substr_count($_POST['seu_textarea'], "\n");
    
18.04.2014 / 02:59