w3resource

PHP: trim() function

Description

The trim() function is used to remove the white spaces and other predefined characters from the left and right sides of a string.

Version:

(PHP 4 and above)

Syntax:

trim(string_name, char_list)

Parameters:

Name Description Required /
Optional
Type
string_name The string to be trimmed. Required String
char_list Specifies the character(s) to remove. Without this remove the following " " an ordinary space.
"\0" - the NUL-byte.
"\t" - tab.
"\n" - line feed.
"\x0B" - a vertical tab.
"\r" - a carriage return.
Optional String

Return value:

The trimmed string.

Value Type: String.

Pictorial Presentation

string_trim

Example - 1:

<?php
$string_name=' Welcome to w3resource.com ';
$new_string=trim($string_name);
echo $new_string;
?>

Output:

Welcome to w3resource.com

View the example in the browser

Example - 2 :

<?php
$string_name="	Welcome to w3resource.com";
$new_string=trim($string_name,"\t");
//echo $new_string;
var_dump($new_string);
?>

Output :

string(25) "Welcome to w3resource.com"

View the example in the browser

See also

PHP Function Reference

Previous: substr
Next: ucfirst



PHP: Tips of the Day

In PHP, there are two versions of logical AND and OR operators.

Operator True if
$a and $b Both $a and $b are true
$a && $b Both $a and $b are true
$a or $b Either $a or $b is true
$a || $b Either $a or $b is true

Note that the && and || opererators have higher precedence than and and or. See table below:

Evaluation Result of $e Evaluated as
$e = false || true True $e = (false || true)
$e = false or true False ($e = false) or true

Because of this it's safer to use && and || instead of and and or.