PHP trim | Remove Characters from Both Sides of String

PHP trim is an inbuilt function in PHP. It removes whitespaces (or other characters) from both the left and right sides of a string. In this article, we will discuss the PHP trim Function. Also, we will discuss a few examples of using it.

To remove characters only from left or right, you can use the following functions:

Syntax

trim($string, $characterList)

Parameters

The PHP trim Function expects two parameters. However, only one parameter is mandatory and the other is optional.

  • $string: The first parameter to the function is the string to operate on. It is a mandatory parameter.
  • $characterList: The second parameter to the function is an optional parameter. It specifies the character list to remove from the string. By default, the function removes all the following characters:
    • “\0” – NULL
    • “\t” – tab
    • “\n” – new line
    • “\x0B” – vertical tab
    • “\r” – carriage return
    • ” ” – ordinary white space

Return Value

The trim function in PHP returns the string after removing whitespaces and all other predefined characters from both ends.

Note: The function returns an empty string when the argument is a null variable.

PHP trim Function

Examples

Let’s discuss a few examples of using the function.

Example 1: Removing Whitespaces

For instance, consider a simple string containing whitespaces on both ends.

<?php

	$string = '   Simple   string ';
	$trimmedString = trim($string);

	var_dump($trimmedString);

?>

In the above example, the function removes whitespaces from both ends of the string.

OUTPUT:
string(15) "Simple   string"

Example 2: Specifying Characters to Remove

Also, we can specify characters to remove by passing the second parameter.

<?php
$str = "Hello World!";
echo $str;
//Remove "He" in "Hello" and "d!" in "World"
echo trim($str,"Hed!");
?>

The above example will print the following:

OUTPUT:
Hello World!
llo Worl

Example 3: Removing Whitespaces from Array of Strings

Similarly, you can remove whitespaces from an array of strings using PHP array_map. We can pass the trim function as callback in array_map function.

<?php

$fruit = array('apple','banana ', ' mango ');

$trimmedArray = array_map('trim', $fruit);
var_dump($trimmedArray);

?>

The above example will print the following:

OUTPUT:

array(3) {
  [0]=>
  string(5) "apple"
  [1]=>
  string(6) "banana"
  [2]=>
  string(5) "mango"
}

Conclusion

In conclusion, we discussed the PHP trim Function. You can read more about it on PHP Official Documentation. Additionally, you can learn about more PHP String Functions on Concatly.

Spread the Knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *