Search code examples
phppreg-replacenewlinecarriage-return

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);

Solution

  • $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/