Home » Php » javascript – Get same result for php `str_len ` as for jQuery `.val().length()`

javascript – Get same result for php `str_len ` as for jQuery `.val().length()`

Posted by: admin July 12, 2020 Leave a comment


I use jQuery to count the value of a textarea on the fly:

function count_chars () {

…then on submit serialize the form, send the text of the textarea via ajax to a php file which then validates the text on the server side. However, I got problems with newlines and spaces.

Of course, if I just get the text “as it is” from the textarea, php will count each new line as two or 4 characters (\n, …). So I tried to replace them with something like this:

strlen(str_replace(array("\r", "\n"), ' ', $text)))

or this:

strlen(preg_replace('/\s+/', ' ', trim($text)))

However, if I got e.g. 10 paragraphs and jQuery returns 2500 characters, php will either return 2510 or 2490, depending if I replace new lines with a space or remove them completely. So the difference is 20, but there are only 10 new lines…?

What am I missing? How can I get php to return the same result as jQuery? Where is the problem, in php or in jQuery?

How to&Answers:

This should work:

strlen(str_replace("\r", '', $text)))


strlen(str_replace(array("\r", "\n"), ' ', $text)))

Here, you’re replacing \r and \n with a space, so the character count doesn’t really change.

strlen(preg_replace('/\s+/', ' ', trim($text)))

Here you are reducing continous whitespace into a single ' '.