Definition and Usage
- PHP Version
- 4+
The trim() function removes whitespace or characters specified by a parameter from both ends of a string.
This function is commonly used to remove unexpected whitespace from the beginning and end of user input strings.
Basic Example
/* Remove whitespace from both ends of a string */
$string = ' hello world ';
$trimmed = trim($string);
var_dump($trimmed); // Output: string(11) "hello world"
/* Remove characters specified by a parameter */
$string = 'hello world';
$trimmed = trim($string, 'he');
var_dump($trimmed); // Output: string(9) "llo world"
/*
* Caution: trim() does not properly handle multibyte characters,
* such as Japanese characters, which may cause encoding issues.
*/
$string = 'ようこそ';
$trimmed = trim($string, 'よう');
var_dump($trimmed); // Output: string(4) "�そ"
Syntax
trim(string $string, string $characters = " \n\r\t\v\x00"): string
Parameters
$string |
Required. The string from which characters will be removed. |
|---|---|
$characters |
Optional. Specifies which characters to remove. If omitted, the following whitespace characters are removed by default:
|
The trim() function does not support multibyte characters, such as Japanese, when removing characters specified by the parameter, so use caution.
Return Values
The trim() function returns the string after removing whitespace or characters specified by the parameter from both ends of the string.
Note that it does not support multibyte characters, such as Japanese, when removing characters specified by the parameter, so use caution.
* Caution: trim() does not properly handle multibyte characters,
* such as Japanese, which may cause garbled output.
*/
$string = 'ようこそ';
$trimmed = trim($string, 'よう');
var_dump($trimmed); // Output: string(4) "�そ"
In such cases, you can handle multibyte characters using functions like preg_replace(), as shown below:
Additional Explanation
The preg_replace() function uses regular expressions to search for patterns within a string and replace them with other text.
$original_string = 'ようこそ。はじめまして!';
$trim_string = preg_replace('/^よう/u', '', $original_string);
var_dump($trim_string); // Output: string(30) "こそ。はじめまして!"
Due to the inconvenience of trim() not supporting multibyte characters for the parameter, this function is mainly used to remove whitespace characters rather than other specified characters.
Practical Examples
The trim() function is primarily used to filter out (remove) whitespace characters—including spaces, tabs, and newlines—from the beginning and end of a string.
This is a common task when handling user input or external data, helping to clean up strings and maintain data consistency.
Here are some practical examples:
User Input Handling
$username = trim($_POST['username']);
$password = trim($_POST['password']);
You can process user-provided input by removing extra spaces from the username and password fields.
Using in Database Queries
$input = ' some value ';
$cleaned_input = trim($input);
$query = "SELECT * FROM table WHERE column = '$cleaned_input'";
When constructing database queries, trim() can be used to preprocess input values.
Text File Processing
$lines = file('example.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$cleaned_lines = array_map(function($line) { return trim($line); }, $lines);
Additional Explanation
The array_map() function applies a given callback function to each element of an array and returns a new array.
This removes leading and trailing whitespace from each line in a text file and stores the cleaned lines in an array. Each line is processed with trim() before being added to the $cleaned_lines array.
References
See also
- PHP substr() Function – Slice Strings by Position and Length
- PHP mb_substr() Function – Multibyte-Safe Alternative to substr()
- PHP str_replace() Function – Replace Text in a String
- PHP preg_replace() Function – Replace Text Using Regular Expressions
- PHP strpos() Function – Find First Substring Index
- PHP mb_strpos() Function – Multibyte-Safe Alternative to strpos()
- PHP stripos() Function – Find First Substring Index (Case-Insensitive)
- PHP mb_stripos() Function – Multibyte-Safe Alternative to stripos()
- PHP str_contains() Function – Check if a String Contains a Substring (Case-Sensitive)