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

23,255

Solution 1

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().

Solution 2

Let's replace not only space but all ASCII Controll Chars.

ex. Space Tab End of Line

$str = preg_replace("/[\\x0-\x20\x7f]/", '', $str);

Solution 3

 array('username','filter','filter'=>'trim')
array('templatename','filter','filter'=>'trim')

Add above lines in rules

Share:
23,255
user3195417
Author by

user3195417

Updated on July 11, 2022

Comments

  • user3195417
    user3195417 almost 2 years

    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"?