Friday, October 17, 2025
HomeLanguagesHow to remove white spaces only beginning/end of a string using PHP...

How to remove white spaces only beginning/end of a string using PHP ?

We have given a string and the task is to remove white space only from beginning of a string or end from a string str in PHP. In order to do this task, we have the following methods in PHP:

Method 1: Using ltrim() Method: The ltrim() method is used to strip whitespace only from the beginning of a string.

Syntax:

ltrim($string, $charlist)

Example :

PHP




<?php
// PHP program to remove white space
// from beginning of a string 
    
$str = "  Geeks  for  Geeks   "; 
    
// Using ltrim() function 
// removes whitespaces from 
// beginning of a string 
$str = ltrim($str);
  
// Printing the result
echo $str; 
  
$len = strlen($str);
  
echo "\nLength of String: ";  
echo $len;
?>


Output

Geeks  for  Geeks   
Length of String: 20

Method 2: Using rtrim() Method: The rtrim() method is used to strip whitespace only from the end of a string.

Syntax:

rtrim($string, $charlist)

Example :

PHP




<?php
// PHP program to remove white space
// from the end of a string 
    
$str = "  Geeks  for  Geeks   "; 
    
// Using rtrim() function to
// remove whitespaces from 
// end of a string 
$str = rtrim($str);
  
// Printing the result
echo $str; 
  
$len = strlen($str); 
echo "\nLength of String : ";  
echo $len;
?>


Output

  Geeks  for  Geeks
Length of String : 19
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS