English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

PHP Basic Tutorial

PHP Advanced Tutorial

PHP & MySQL

PHP Reference Manual

PHP trim() Function Usage and Example

   PHP String Function Manual

    The trim() function is used to remove whitespace characters (or other specified characters) at the beginning and end of the string

Syntax

trim(string,charlist)

Definition and Usage

It is used to delete spaces and other characters

Related Functions:

  • ltrim() - Remove whitespace characters at the beginning of the string or other predefined characters.

  • rtrim() - Remove whitespace characters at the end of the string or other predefined characters.

Return Value

It returns the modified string

Parameter

Serial NumberParameter and Description
1

string

Specify the string to be checked

2

charlist

Specify the characters to be removed, specify which characters to remove from the string. If the parameter is omitted, the following characters are removed:

  • "\0" - NULL

  • "\t" - Tab

  • "\n" - Newline

  • "\x0B" - Vertical tab

  • "\r" - Carriage return

  • " " - Space

Online example

Try the following example

<?php
     
    //Delete spaces at both ends of the string
    $str = " Hello World! ";
    echo trim($str) . "<br>";
    //Remove 'www.' from the domain name
    $input = "www.oldtoolbag.com";
    echo trim($input,"www.") . "<br>";
    //Remove newline characters (\n) from both sides of the string:
    $str = "\n\n\nHello World!\n\n\n";
    echo "Without using trim: " . $str;
    echo "<br>";
    echo "After using trim: " . trim($str);
?>
Test and see‹/›

Output result

Hello World!
oldtoolbag.com
Without using trim: 
Hello World!
After using trim: Hello World!

PHP String Function Manual