Search code examples
phpstringtrim

PHP function trim() not stripping whitespace from the middle of the string


I have some pretty straight-forward code, but something's going wrong. The following code

$title = $_POST['templatename'];
$user = $_POST['username'];
$selectedcoordinates = $_POST['templatestring'];

$title = trim($title);
$user = trim($user);


$filename = $title . "_by_" . $user;

var_dump($title);
var_dump($user);
var_dump($filename);

returns this:

string(11) "Single Tile"
string(6) "Author"
string(21) "Single Tile_by_Author" 

where the values originate from a HTML form. Why doesn't "Single Tile" become "SingleTile"?


Solution

  • The function trim() removes only the spaces (and control characters such as \n) from the beginning and the end of the string.

    $title = str_replace(" ", "", trim($title));
    $user = str_replace(" ", "", trim($user));
    

    I just wanted to attack the problem. So, the solution may look bad. Anyways, the best use for this is by using this way:

    $title = str_replace(" ", "", $title);
    $user = str_replace(" ", "", $user);
    

    I removed the trim() function because str_replace() does the job of trim().