Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

function count_chars () {
    count_chars=$('#text_textarea').val().length;
}

...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?

like image 250
Chris Avatar asked Aug 14 '12 10:08

Chris


1 Answers

This should work:

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

Explanation:

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 ' '.

like image 129
Dogbert Avatar answered Nov 05 '22 11:11

Dogbert