Draw a frame around a line of text, using string repetition and measuring.
What to build
A program that prints a line of text inside a box.
Requirements
- Read one line of text.
- Print a top border, the text between bars with one space on each side, and a bottom border. The border has
+at both ends and as many dashes as the text length plus two.
Input
One line of text.
Output
Three lines.
Constraints
The text has 1 to 60 characters.
Example
Input:
PHP
Output:
+-----+
| PHP |
+-----+
Why it works
strlen gives the width, and str_repeat builds a border of exactly the right size.
Examples
Example 1 · Input
PHP
Expected output
+-----+ | PHP | +-----+
Example 2 · Input
Hello, world
Expected output
+--------------+ | Hello, world | +--------------+
Hints
Hint 1
The border is a plus, then dashes, then a plus: str_repeat("-", strlen($text) + 2).
Hint 2
The middle line is a bar, a space, the text, a space and a bar.
Solution
Show one correct solution (try it yourself first)
<?php
$text = trim(fgets(STDIN));
$border = "+" . str_repeat("-", strlen($text) + 2) . "+";
echo $border, "\n";
echo "| ", $text, " |\n";
echo $border, "\n";