Count lines with PHP and JS

Asked

Viewed 2,243 times

1

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

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

  • I don’t quite understand your question, but do you want to create a line break counter? but count lines than? can you give an example? Obs:I cannot comment on your question as I do not have enough reputation for it.

  • @Jahnkrauss I need to create a texte area and while I type I need a function that records the number of lines (each line I type) and that records this value in a variable so I can automatically print it with Javascript, as if it were a line counter

  • @user7162 Would that be something? function countLines(area)
{
var text = area.value.replace(/\s+$/g,"")
var split = text.split("\n")
return split.length
} Sorry for formatting but I don’t know why I’m not able to format the text after just sending the result to a php variable.

  • 1

    I added an answer, but I’m not sure what you want. If you want to display line-by-line numbering, specify better in the question.

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 demonstration on SQL Fiddle

Note: the line count will be sent in a field hidden, to answer the question, however the ideal is to reconnect via PHP, and not send the value, as this can be modified manually and/ or simulated.

PHP:

(we are not using the HTML hidden field, but "reconnecting" 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;
?>

0

To get javascript for the total number of lines in a textarea, you can do something like:

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

Example: http://jsfiddle.net/yTRwD/

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

substr_count($_POST['seu_textarea'], "\n");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.