-1

So I have an input form where the user would enter a username, after submitting, the site would gather information based on the username, however, if there is a space within the username, the username becomes void (non-existant). How would I add a behaviour in PHP that rids of any and all spaces, so that instead of the final submitted username being john doe, it would be johndoe.


Here's my form code:

<form action="php.php" method="GET">
  <div class="form-group">
    <label for="username">Username:</label>
    <input type="text" class="form-control" id="username" name="username" placeholder="Enter username" required>
  </div>
  <button type="submit" class="btn btn-default">Submit</button>
</form>

And here's the php.php file code:

//I GUESS THIS IS WHERE THE TRIMMING SHOULD HAPPEN?
<?php
//error_reporting(E_ALL & ~E_NOTICE);
// Load the username from somewhere
if (
$username = $_GET["username"]
) {
    //do nothing 
} else {
    //$username = "notch";
  echo "Oops! Something went wrong!";
}
?>
6

2 Answers 2

6

1. If you are talking about leading or trailing spaces then use trim() function.

$username =trim($username);

2 But if you are talking about middle spaces then do with preg_replace():-

$username = preg_replace('/\s+/', ' ', $username);

3 You can go with str_replace() also:-

$username = str_replace(' ','',$username);

Note:- Here $username is your user name that you are going to use.

Also you can merge first with second or third to get fully clean username without leading trailing and middle spaces. like this:-

$username = trim(preg_replace('/\s+/', ' ', $username));

There's a little typo above, but edits in stackoverflow must be at least 6 characters, so I made that non-sense words...

0
3

Use the String Replace function to replace all occurrences of a space in a string with an empty string (nothing):

$string = 'My Name';
$noSpaces = str_replace(' ', '', $string);
echo $noSpaces; // echos 'MyName'
3
  • So, in my case, I would simply do $username = str_replace(' ', '', $string); ? May 9, 2015 at 23:48
  • yes, $username would now contain no spaces
    – user1247034
    May 9, 2015 at 23:51
  • Yep. Thanks, that's done the trick! Will mark in 4 mins, as that's when it'll allow me too! May 9, 2015 at 23:54

Not the answer you're looking for? Browse other questions tagged or ask your own question.