PHP String ltrim() Function



The PHP String ltrim() function is used to remove whitespaces or other characters (if given) from the left side of a string. The function accepts two parameters, as seen by the syntax below. While one of these paarmeters is required and the other one is optional.

Syntax

Below is the syntax of the PHP String ltrim() function −

string ltrim ( string $str [, string $character_mask ] )

Parameters

Here are the parameters of the ltrim() function −

  • $str − (Required) It contains the information about string input.

  • $character_mask − (Optional) You can also specify the characters you want to strip.

If $character_mask is omitted so all of the below characters are removed −

  • "\0" - NULL

  • "\t" - tab

  • "\n" - new line

  • "\x0B" - vertical tab

  • "\r" - carriage return

  • " " - ordinary white space

Return Value

The ltrim() function returns a string with whitespace stripped from the beginning of str.

PHP Version

First introduced in core PHP 4, the ltrim() function continues to function easily in PHP 5, PHP 7, and PHP 8.

Example 1

Here is the basic example of the PHP String ltrim() function to remove the whitespaces from the given string.

<?php
   $string = "            Tutorials Point"; 
   
   echo "Contribute to ".ltrim($string); 
?>

Output

Here is the outcome of the following code −

Contribute to Tutorials Point

Example 2

In the below PHP code we will try to use the ltrim() function and remove other characters from the mentioned string.

<?php
   $string = "!!! (( !!)) Tutorialspoint"; 
     
   // The characters '!', '(', ')', and '' 
   // have been directed to be removed from the string's beginning.
   echo ltrim($string, "! ()"); 
?> 

Output

This will generate the below output −

Tutorialspoint

Example 3

Now the below code removes specific characters from the beginning of the string with the help of the $character_mask parameter in ltrim() function.

<?php
   $string = "abcHello, World!";
   $result = ltrim($string, "abc");
   echo $result; 
?> 

Output

This will create the below output −

Hello, World!

Example 4

This program shows removing multiple specific characters, like whitespace from the beginning of a string using the ltrim() function.

<?php
   $string = " 123abc---Hello, Tutorialspoint!";
   
   // Define the characters to remove
   $character_mask = " 123abc-"; 

   $result = ltrim($string, $character_mask);
   echo $result; 
?> 

Output

Following is the output of the above code −

   Hello, Tutorialspoint!
php_function_reference.htm
Advertisements