Summary: in this tutorial, you’ll learn how to use the PHP trim()
function to remove whitespace or other characters from both ends of a string.
Introduction to the PHP trim() function
The trim()
function removes the whitespaces or other characters from the beginning and end of a string.
Here’s the syntax of the trim()
function:
trim ( string $string , string $characters = " \n\r\t\v\0" ) : string
Code language: PHP (php)
The trim()
function has two parameters:
$string
is the input string that will be trimmed.$characters
argument is optional. It specifies which character to remove from both ends of the$string
.
By default, the trim()
function removes the following characters:
Character | ASCII | Hex | Description |
---|---|---|---|
” “ | 32 | 0x20 | a space |
“\t” | 9 | 0x09 | a tab |
“\n” | 10 | 0x0A | a new line |
“\r” | 13 | 0x0D | a return |
“\0” | 0 | 0x00 | a NUL-byte |
“\v” | 11 | 0x0B | a vertical tab |
If you want to remove other characters, you can specify them in the $characters
argument.
To specify a range of characters to remove, you can use the ‘..’. For example, to remove all ASCII control characters from both ends of a string, you use the following value for the $characters argument:
'\x00..\x1F'
Code language: PHP (php)
It’s important to note that the trim()
function doesn’t change the input string. It returns a new string with all the $characters
removed.
PHP trim() function examples
Let’s take some examples of using the PHP trim()
function.
1) Using the PHP trim() function to remove whitespace from both ends of a string
The following example uses the trim()
function to remove spaces from the beginning and the end of a string:
<?php
$str = ' PHP ';
$new_str = trim($str);
var_dump($new_str);
Code language: PHP (php)
Output:
string(3) "PHP"
Code language: plaintext (plaintext)
2) Using the PHP trim() function to remove other characters
Suppose you have the following URL:
https://www.phptutorial.net/api/v1/posts/
Code language: PHP (php)
To get the request URI, you access the $_SERVER
array with the key 'REQUEST_URI'
:
<?php
$uri = $_SERVER['REQUEST_URI'];
echo $uri;
Code language: PHP (php)
Output:
/api/v1/posts/
Code language: plaintext (plaintext)
The URI contains both leading and trailing slashes.
To remove the slashes (/
) from both ends of the URI, you can use the trim()
function:
<?php
$uri = $_SERVER['REQUEST_URI'];
echo trim($uri,'/');
Code language: PHP (php)
Output:
api/v1/posts
Code language: plaintext (plaintext)
Summary
- Use the PHP
trim()
function to remove whitespaces or other characters from both ends of a string.