Categories
Coding PHP

PHP Count characters in string!

During one of my courses this morning the instructor wanted a simple form input made with a text box to allow a string of text to be entered via a submit button. Then it will display the number of characters in the string. Bonus was a selector to optionally count spaces y/n. I made a couple versions, my second one was much shorter using a ternary operator.

This is two files and note the form is very simple just to get it done fast. My code ide PHPStorm gives me alerts that my form is sloppy, ftw.

//The PHP code
$result = "";
if(isset($_POST['submit'])){
    $string = $_POST['string'];
    $spaces = $_POST['spaces'];
    $result = ($spaces == "n") ? strlen($string) - substr_count($string, ' ') : strlen($string);
    echo $string . "<br>";
    echo "The string above is " . $result . " characters long with " . str_word_count($string) . "  words. Counting spaces (" . $spaces . ")";
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>How long is the string?</title>
</head>
    <body>
        <h1>Counts characters in string!</h1>
            <form action="string_process.php" method="post">
                <label>
                    Enter a string of text!
                    <input type="text" name="string">
                </label>
                Count spaces?
                Yes<input type="radio" name="spaces" value="y">
                No<input type="radio" name="spaces" value="n">
                <input type="submit" name="submit" value="submit">
            </form>

    </body>
</html>

Results below for ‘What is this about?’ entered.

What is this about?
The string above is 16 characters long with 4 words. Counting spaces (n)

So after I do my own code for challenge I watch the instructor do his version. He did it all in one file and his space removal code was a different method.

/* He used str_replace(), there is always another way 
to do anything in coding. 
I used strlen($string) - substr_count($string, ' '). 
His is much shorter. */

if($spaces == 'no'){
$string = str_replace(" ", "", $string);
}

Leave a Reply

Your email address will not be published. Required fields are marked *

+ 34 = 38