Reputation: 4633
<form action="class.php" method="POST">
thread link:
<br>
<input type="text" name="thread">
<input type="submit" value="Submit">
</form>
I have this simple form. Upon entering a string starting with many spaces, something like
" test"
my PHP code
echo 'test:'.$_POST['thread'];
will print test: test
. It will erase all spaces except one.
Where did all the spaces go and why does this happen?
Upvotes: 1
Views: 81
Reputation: 19915
This is the most basic thing about HTML. Any whitespace is equivalent and is treated as a single space.
You should never use multiple spaces to try to layout your text in HTML ( like you could do in Word for instance ). You should use css styles like margin or padding instead.
The answers that propose to replace the spaces with & nbsp; are correct, but they leave you on the wrong track.
Upvotes: 0
Reputation: 201628
The form does not delete spaces. Neither does your PHP code. The spaces are still there in resulting HTML document (generated by your PHP code in response to form submission). They just get rendered as a single space, since in most contexts, any sequence of whitespace characters in HTML content is equivalent to a single space. This is defined in CSS 2.1 spec, in the description of the white-space
property.
Thus, to prevent the collapse of spaces, the simple way is to set white-space: pre
in CSS. It also prevents line breaks in the content, but this is probably not a problem here. Using the pre
element in HTML causes this setting, but it also sets font family to monospace.
So this is just a matter of HTML and CSS, independently of PHP. Example:
<p> Hello world!</p>
<p style="white-space: pre"> Hello world!</p>
Upvotes: 2
Reputation: 363
You need to convert whitespaces to html entities
$thread = str_replace(' ', ' ', $_POST['thread'])
and now echo 'test:'.$thread
will output your text with whitespaces.
Upvotes: 1
Reputation: 7739
Specification of HTMLs tells, renderer removes multiple spaces. That is useful in some cases. To avoid that, you can place content of this field in <pre></pre>
block. Like that:
echo '<pre>test:'.$_POST['thread'].'</pre>';
Upvotes: 4