Names typed by users come with extra spaces and odd capital letters. Clean one.
What to build
A program that tidies a name.
Requirements
- Read one line.
- Remove spaces at both ends, reduce every group of spaces inside to one space, and print each word with a capital first letter and the other letters in lower case.
Input
One line: the name.
Output
One line.
Constraints
The line has at most 80 characters and at least one letter.
Example
Input:
aDA lOVELACE
Output:
Ada Lovelace
Why it works
strtolower and ucwords fix the capital letters, and splitting on spaces removes the empty parts.
Examples
Example 1 · Input
aDA lOVELACE
Expected output
Ada Lovelace
Example 2 · Input
grace hopper
Expected output
Grace Hopper
Hints
Hint 1
Use trim, strtolower and ucwords.
Hint 2
Split on spaces and drop empty parts to remove extra spaces inside the name.
Solution
Show one correct solution (try it yourself first)
<?php
$line = strtolower(trim(fgets(STDIN)));
$words = array_filter(explode(" ", $line), fn($w) => $w !== "");
echo ucwords(implode(" ", $words)), "\n";