Summary: in this tutorial, you’ll learn how to use the PHP ltrim()
function to remove whitespace characters or other characters from the beginning of a string.
Introduction to the PHP ltrim() function #
The PHP ltrim()
function removes the whitespace characters or other characters from the beginning of a string.
Here’s the syntax of the ltrim()
function:
ltrim ( string $string , string $characters = " \n\r\t\v\0" ) : string
Code language: PHP (php)
The ltrim()
has the following parameters:
$string
is the input string$characters
is one or more characters that you want to remove from the beginning of the string.
By default, the ltrim()
function strips the characters in the list " \n\r\t\v\0"
from the beginning of the string.
If you want to strip other characters, you can specify them in the $characters
argument.
To remove a set of characters, you can use the ..
syntax. For example, to remove all characters from a to z, you pass the the following string to the $characters argument:
'a..z'
Code language: PHP (php)
It’s important to notice that the ltrim()
function doesn’t modify the input string ($string
). Instead, it returns a new string with the characters specified in the $characters
removed.
PHP ltrim() function examples #
Let’s take several examples of using the ltrim()
function.
1) Using the PHP ltrim() function to remove whitespace characters #
This example uses the ltrim()
function to strip all the space characters from the beginning of a string:
<?php
$title = ' PHP tutorial';
$clean_title = ltrim($title);
var_dump($clean_title);
Code language: PHP (php)
Output:
string(12) "PHP tutorial"
Code language: PHP (php)
2) Using the PHP ltrim() function to remove other characters #
The following example uses the ltrim() function to remove the slash (/
) at the beginning of a string:
<?php
$uri = '/php-ltrim';
$new_uri = ltrim($uri, '/');
echo $new_uri;
Code language: PHP (php)
Output:
php-ltrim
Code language: PHP (php)
Summary #
- Use the PHP
ltrim()
function to remove the whitespace characters or other characters from the beginning of a string.