PHP Function Reference

PHP trim() Function



The PHP trim() function returns a string which is trimmed version of the specified string. It removes whitespaces or other characters from both sides of the string.

Syntax

trim(string, characters)

Parameters

string Required. Specify the string to trim.
Characters Optional. Specify characters which need to be trimmed from the string. Without this parameter, the function will strip following characters:
  • " " - an ordinary space.
  • "\t" - a tab.
  • "\n" - a new line (line feed).
  • "\r" - a carriage return.
  • "\0" - the NULL-byte.
  • "\v" - a vertical tab.

Return Value

Returns the trimmed version of the specified string.

Example:

In the example below, trim() function is used to trim the given string.

<?php
$MyString = "    Hello World!.    ";
$NewString = trim($MyString);

echo $NewString."\n";
?>

The output of the above code will be:

Hello World!.

Example:

We can also specify the characters which need to be trimmed from the string as shown in the example below.

<?php
$MyString = ",*#Hello World!#@!";
$NewString = trim($MyString, ",*#@!");

echo $NewString."\n";
?>

The output of the above code will be:

Hello World

Example: Trimming array values

Consider one more example where this function is used to trim the array values.

<?php
function trim_value(&$value) { 
  $value = trim($value, "# @*"); 
}

$arr = array("#John", " Marry ", " Kim*", "@Jo");
print_r($arr);

echo "\n";

//trimming the array values 
array_walk($arr, 'trim_value');
print_r($arr);
?>

The output of the above code will be:

Array
(
    [0] => #John
    [1] =>  Marry 
    [2] =>  Kim*
    [3] => @Jo
)

Array
(
    [0] => John
    [1] => Marry
    [2] => Kim
    [3] => Jo
)

❮ PHP String Reference