EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

trim() in PHP

Home » Software Development » Software Development Tutorials » PHP Tutorial » trim() in PHP

trim() in PHP

Introduction to trim() in PHP

trim() is one of the in-built functions of PHP whose purpose is to trim the white spaces and also other predefined characters from both the left and right side of a string. Hence it is very useful in various scenarios such as:

  • To clean up input given by the user like the text field values which are submitted.
  • To remove line break characters at the end of the line which is not required.
  • To parse or to make sure that the string is in the required format before it is passed on to another program.

Syntax with Parameters

Following is a syntax with parameters:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax:

trim ( string $str [, string $character_mask = " \t\n\r\0\x0B" ] ) : string

As shown above, input parameters for this trim function include the input string which will be trimmed of its whitespaces from the beginning and the end of its string $str. The second parameter in the syntax is optional and is used to define explicitly what characters should be trimmed exactly.

Hence without the second parameter, the trim function trims the below parameters by default:

  • ” ” (ASCII 32 (0x20)) which is a normal space character.
  • “\t” (ASCII 9 (0x09)) which is a tab character
  • “\n” (ASCII 10 (0x0A)) which represents new line character.
  • “\r” (ASCII 13 (0x0D)) which is a carriage return character.
  • “\0” (ASCII 0 (0x00)) which is called the NULL byte.
  • “\x0B” (ASCII 11 (0x0B)) which represents a vertical tab.

Parameters Required:

  • str: This is the input string that will be trimmed of whitespaces.
  • character_mask: This is an optional field that can also be specified using this parameter. All the characters mentioned inside the braces will be trimmed. With this, we can also specify a wide range of characters.
  • Return values: Outputs a trimmed string.

Types of trim() in PHP:

There are 3 different types of trim() function which can be used for the below-mentioned purposes:

  • trim(): This is a normal one and can be used to trim from both the beginning and end of a string.
  • ltrim(): This is used to trim characters from the beginning of the input string
  • rtrim(): This is used to trim characters from the end of the input string.

Examples of trim() in PHP

Given below are the examples of trim() in PHP:

Example #1 – To remove the newline character.

Code:

<?php
$str = "\n\nDemo text!\n\n";
echo "Trim: " . ($str);
?>

Output:

trim() in php 1

In the above example, we are showcasing to see the output without the use of the trim() function. In the string assigned we are displaying newlines as part of the sentence for testing purposes. The same thing can be seen in the output.

<?php
$str = "\n\nDemo text!\n\n";
echo "Trim: " . trim($str);
?>

Output:

trim() in php 2

The above example displays a basic program for the usability of trim() function. Here $str is the variable to which the required string or a sentence is to be declared. After using the trim function as seen in the output it trims all the \n present in the input string and displays the string.

Popular Course in this category
PHP Training (5 Courses, 3 Project)5 Online Courses | 3 Hands-on Project | 28+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (5,726 ratings)
Course Price

View Course

Related Courses
Java Servlet Training (6 Courses, 12 Projects)All in One Software Development Bundle (600+ Courses, 50+ projects)

Example #2 – To remove tab character.

Code:

<?php
$str1=" Just an example";
$str_new=trim($str1,"\t");
//echo $str_new;
var_dump($str_new);
?>

Output:

trim() in php 3

In the above example, we are using the trim function to remove tab (“\t”) character by explicitly specifying the character in the second parameter of the trim function as seen. First, we are assigning the required string to a parameter called str1, and then using another parameter $str_new to append a tab at the end of the $str1. Simultaneously trim function is used which removes this tab character from the end of the string.

When we try the same code by removing the trim function we can see that an extra tab will get printed at the end of the string as we have appended it in a $str_new parameter. Hence trim functionality is verified.

Example #3 – To remove blank space characters.

Code:

<?php
$str = "
No blank space
";
// Displays "No blank space"
echo trim( $str );
?>

Output:

No blank space

In the above example, we can see that the input string has a lot of blank spaces at its beginning. Hence to remove this we are using the trim function. As seen in the output, all the blank spaces from the beginning have been trimmed out and the proper input string is displayed. Also please note that only the whitespaces between the start and end of the string are trimmed and not the ones in between the sentence. Like the spaces in between “Example” and “to” are still the same.

Example #4 – To remove more than one special character.

Code:

<?php
$str = "\r\r Removing both characters \n\n";
// Displays " Removing both characters "
echo trim( $str, "\r\n" );
?>

Output:

Removing characters

In the above example, we can see that the input string has 2 special characters “\n” and “\r”. Hence, we will use the optional second parameter in the trim function to explicitly specify a range of characters (“\n” and “\r” in this case) which needs to be trimmed. As we can see in the output, the mentioned characters are trimmed.

Example #5 – To display trimming of numbers as well.

Code:

<?php
$str = "123 Just an example 456";
// Displays "Just an example"
echo trim( $str, " 0..9" );
?>

Output:

trimming of number as well

By using the trim() function we can also trim the numbers by specifying it in the second parameter list. It also allows us the use of dot notation using which if we specify as “0..9” the function removes all numbers in the input string ranging from 0 to 9. Hence in the above example using the above method it will trim the numbers “123” and “456” from the beginning and the end of the input string respectively.

Example #6 – To trim using rtrim() and ltrim()

Code:

<?php
$str = " Example for ltrim ";
// Displays "Example for ltrim "
echo ltrim( $str );
echo "\n";
$str = "452 Example for rtrim 456";
// Displays "123 Example for rtrim"
echo rtrim( $str, " 0..9" );
?>

Output:

ltrim

As seen in the above example when ltrim is used, it only trims the extra spaces at the starting of the string. Similarly, when rtrim is used by specifying to trim numbers from 0 to 9, it only trims the numbers from the end of the string.

Conclusion

In this article, we have went through in-depth the usage of trim(), ltrim() and rtrim() functions which are basically used to remove the characters which are not required from a string. We have also seen how to specify our own whitespace character for trimming.

Recommended Articles

This is a guide to the trim() in PHP. Here we discuss the basic concept, parameters, types, and examples of trim() in PHP. You may also have a look at the following articles to learn more –

  1. PHP String Functions
  2. Arithmetic Operators in PHP
  3. Fibonacci Series PHP
  4. PHP ucfirst()

PHP Training (5 Courses, 3 Project)

5 Online Courses

3 Hands-on Project

28+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
PHP Tutorial
  • Functions
    • Functions in PHP
    • PHP Math Functions
    • PHP Recursive Function
    • PHP String Functions
    • Hashing Function in PHP
    • Date Function in PHP
    • PHP Anonymous Function
    • Calendar in PHP
    • PHP Call Function
    • PHP Pass by Reference
    • PHP ucfirst()
    • PHP ucwords()
    • trim() in PHP
    • isset() Function in PHP
    • PHP replace
    • PHP fpm
    • PHP strpos
    • preg_match in PHP
    • PHP preg_replace()
    • PHP ob_start()
    • PHP Reflection
    • PHP Split String
    • PHP URL
    • PHP preg_match_all
    • PHP strtoupper()
    • PHP preg_split()
    • PHP substr_replace()
    • PHP setlocale()
    • PHP substr_count()
    • PHP Serialize
    • PHP strlen()
    • PHP async
    • PHP Date Time Functions
    • PHP timezone
    • PHP Data Object
    • print_r() in PHP
    • PHP header()
    • PHP strip_tags()
    • PHP chop()
    • PHP MD5()
    • PHP unset()
    • PHP crypt()
    • PHP wordwrap()
    • PHP is_null()
    • PHP strtok()
    • PHP bin2hex()
    • PHP parse_str()
    • PHP levenshtein()
    • PHP addslashes()
    • PHP strtotime
    • PHP sha1()
    • PHP explode()
    • PHP sscanf()
    • PHP require_once
    • PHP Zip Files
    • PHP $_SERVER
    • PHP $_POST
    • PHP Include and Require
    • PHP POST Method
  • PHP Basic
    • Introduction To PHP
    • What is PHP
    • PHP Keywords
    • Advantages of PHP
    • Career In PHP
    • Comments in PHP
    • PHP Commands
    • PHP Frameworks
    • PHP Compiler
    • Variables in PHP
    • PHP Superglobal Variables
    • PHP Versions
    • Object in PHP
    • What is Drupal
    • Top PHP Frameworks
    • WebStorm IDE
    • What is phpMyAdmin?
    • PhpStorm
    • Install phpMyAdmin
    • Phalcon Model
  • Data Types
    • PHP Data Types
    • PHP Integer
    • PHP Booleans
  • Operators
    • PHP Operators
    • Arithmetic Operators in PHP
    • Comparison Operators in PHP
    • Logical Operators in PHP
    • Bitwise Operators in PHP
    • Ternary Operator in PHP
    • PHP String Operators
  • Control Statements
    • Control Statement in PHP
    • PHP if Statement
    • if else Statement in PHP
    • elseif in PHP
    • PHP Switch Statement
    • Continue in PHP
    • Break in PHP
  • Loops
    • PHP Loops
    • For Loop in PHP
    • PHP Do While Loop
    • PHP While Loop
    • While Loop in PHP
    • Foreach Loop in PHP
  • Constructor
    • Constructor in PHP
    • Destructor in PHP
  • State Management
    • Cookie in PHP
    • Sessions in PHP
  • Array
    • What is PHP Array
    • Arrays in PHP
    • 2D Arrays in PHP
    • Associative Array in PHP 
    • Multidimensional Array in PHP
    • Indexed Array in PHP
    • PHP Array Functions
    • PHP unset Array
    • PHP Append Array
    • PHP Array Search
    • PHP Split Array
    • PHP array_push()
    • PHP array_pop()
  • Advanced
    • Overloading in PHP
    • Overriding in PHP
    • Method Overloading in PHP
    • Inheritance in PHP
    • Multiple Inheritance in PHP
    • PHP Interface
    • Encapsulation in PHP
    • PHP Constants
    • PHP Magic Constants
    • PHP Regular Expressions
    • PHP GET Method
    • PHP Annotations
    • PHP Encryption
    • PHP file Functions
    • PHP readfile
    • PHP?Write File
    • PHP Append File
    • PHP Type Hinting
    • PHP Filters
    • PHP Float
    • PHP Form
    • PHP Form Validation
    • Sorting in PHP
    • PHP usort()
    • PHP Stack Trace
    • PHP Stack Overflow
    • PHP Pagination
    • PHP implode
    • Polymorphism in PHP
    • Abstract Class in PHP
    • PHP Final Class
    • PHP Custom Exception
    • error_reporting() in PHP
    • PHP Log Errors
    • Access Modifiers in PHP
    • PHP Change Date Format
    • Static Method in PHP
    • PHP File Handling
    • PHP Output Buffering
    • Get IP Address in PHP
    • Upload a File in PHP
    • String in PHP
    • Public Function in PHP
    • Private in PHP
    • Protected in PHP
    • basename in PHP
    • Validation in PHP
    • PHP mail()
    • PHP Email Form
    • PHP Directory
    • PHP Create Session
    • PHP include_once
    • PHP json_decode
    • PHP XMLWriter
    • PHP XML Reader
    • PHP XML Parser
    • PHP XML into Array
    • Phalcon Framework
  • Programs
    • Patterns in PHP
    • Star Patterns in PHP
    • Swapping in PHP
    • Fibonacci Series PHP
    • Factorial in PHP
    • Reverse String in PHP
    • Square Root in PHP
    • Random Number Generator in PHP
    • Palindrome in PHP
    • Prime Numbers in PHP
    • Armstrong Number in PHP
    • Socket Programming in PHP
    • Login Page in PHP
    • PHP Login Template
    • PHP Object to String
  • Database
    • PHP Database Connection
    • How to Connect Database to PHP
  • Interview Questions
    • PHP Interview Questions
    • PHP OOP Interview Questions
    • CakePHP Interview Questions
    • Core PHP Interview Questions

Related Courses

PHP Training Course

Java Servlet Training

Software Development Course Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - PHP Training (5 Courses, 3 Project) Learn More