user1228907
user1228907

Reputation: 399

Remove new line and carriage return characters in a string

I'm trying to count the characters in a textarea, but it also counts "\n" and "\r" as characters; how would I remove them in order to count just the actual text input?

$pure_chars = preg_replace("/\r\n/", "", $_POST['comment']);
echo strlen($pure_chars);

Upvotes: 0

Views: 5537

Answers (2)

mickmackusa
mickmackusa

Reputation: 47894

You can remove all vertical whitespaces with \v or all sequences of newlines (regardless of operating system) with the \R metacharacter which matches \n, \r and \r\n.

I recommend using the "one or more" quanitifier + so that longer potential matches are made and therefore fewer potential replacements.

$pure_chars = preg_replace('/\v+/', '', $_POST['comment']);

or

$pure_chars = preg_replace('/\R+/', '', $_POST['comment']);

Here is a popular demonstration of \R.

Upvotes: 0

jcaron
jcaron

Reputation: 17710

$pure_chars = preg_replace('/[\r\n]+/','', $string)

Note that you're still counting spaces, punctuation, etc, so it's really a matter of deciding what you really want to count. If you want to exclude anything that isn't a letter or a digit, use /\W/

Upvotes: 2

Related Questions