How to remove carriage returns

25 views
Skip to first unread message

Da-Omiete Iboroma

unread,
Oct 1, 2015, 7:23:27 AM10/1/15
to Professional PHP Developers, Robert Gonzalez
Hello, please I am trying to remove carriage return from the input of a textarea.  I want to just count the words. If the words are more than 60, an error message is displayed. But the programme keeps counting the carriage returns. I want to remove the carriage returns then count the words to see if they are more than 60.  I am using the following codes.
if ($_POST["description"])

{
$string = $_POST["description"];
//$string = preg_replace("/(\r\n){3,}/","",trim($text));
//$string = str_replace("\r", '', $text);
//$string = trim(preg_replace('/\s\s+/', ' ', $string));
$string = trim(preg_replace('/\s+/', ' ', $string));
$check = str_word_count($string);
if ($check > 60)
{
$brief_60_err = "<p class=\"notice\">The abstract is <span class=\"blue\">$check</span> words. Reduce it to 60 words</p>";
$send ="no";
}


}
thanks

Robert Gonzalez

unread,
Oct 1, 2015, 11:00:48 AM10/1/15
to Da-Omiete Iboroma, Professional PHP Developers
What you want to do is massage your string a little bit in order to get at what you want. Also remember that different platforms treat new lines differently, so you need to handle carriage return/line feeds, carriage returns and line fields as separate characters:

/**
 * Gets a count of words in an input string
 * @param string $input The string of text to get the count of words from
 * @return int
 */
function getInputWordCount($input) {
    // Start with some simple validation
    // http://php.net/is_string
    if (is_string($input)) {
        return 0;
    }

    // Start with stripping tags for sanitization
    // http://php.net/strip_tags
    $input = strip_tags($input)

    // Now replace carriage return/new line characters, first in combination
    // then individually since each platform treats these differently
    // http://php.net/str_replace
    $input = str_replace(array("\r\n", "\n", "\r"), ' ', $input);

    // Now trim the empty spaces of the ends of the string so we have just a 
    // single bounded string of words
    // http://php.net/trim
    $input = trim($input, ' ');

    // Explode on the space character to get an array of just the words
    // http://php.net/explode
    $words = explode(' ', $input);

    // Lastly, get the count of the array to know how many words are in it
    // http://php.net/count
    // http://php.net/sizeof
    $count = count($words);

    return $count
}

--

Robert Gonzalez
   

Robert Gonzalez

unread,
Oct 1, 2015, 11:01:14 AM10/1/15
to Da-Omiete Iboroma, Professional PHP Developers
Make sure to run that code chunk through a linter. I can already see two places where I forgot the ending semicolon.
Reply all
Reply to author
Forward
0 new messages