Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

php

trim

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

like image 343
user3195417 Avatar asked Jan 19 '14 15:01

user3195417


People also ask

How do I strip whitespace in PHP?

The trim() function removes whitespace and other predefined characters from both sides of a string. Related functions: ltrim() - Removes whitespace or other predefined characters from the left side of a string.

How do you trim white spaces from a string?

trim() The trim() method removes whitespace from both ends of a string and returns a new string, without modifying the original string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.)

How do you strip whitespace or other characters from the beginning and end of a string?

Use the . lstrip() method to remove whitespace and characters only from the beginning of a string. Use the . rstrip() method to remove whitespace and characters only from the end of a string.

Which PHP function is used to remove white spaces in the beginning and the end of a string?

PHP's trim() function removes all whitespace from the beginning and the end of a string.


1 Answers

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

like image 56
Praveen Kumar Purushothaman Avatar answered Sep 27 '22 19:09

Praveen Kumar Purushothaman