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 the beginning of a string or the end from a string str in PHP. In order to do this task, we have the following methods in PHP:
Table of Content
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 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 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
Method 3: Using a Custom Regular Expression with preg_replace()
Using preg_replace() with a custom regular expression /^\s+|\s+$/u removes whitespace from the beginning and end of a string in PHP. This method ensures precise trimming by matching and replacing leading and trailing whitespace characters.
Example
<?php
$string = " Hello, World! ";
$trimmedString = preg_replace('/^\s+|\s+$/u', '', $string);
echo $trimmedString;
?>
Output
Hello, World!
Method 4: Using trim() Method
The trim() method in PHP is used to strip whitespace (or other characters) from both the beginning and end of a string. This method is a straightforward and efficient way to clean up the string.
Syntax:
trim($string, $charlist)
Example: The trim() function is highly useful when you need to remove unwanted whitespace from both ends of a string, making it another effective approach for string manipulation in PHP.
<?php
// Declare a string with whitespace at the beginning and end
$string = " Hello World! ";
// Remove whitespace from both the beginning and end of the string
$trimmedString = trim($string);
// Output the result
echo $trimmedString;
?>
Output
Hello World!
Method 5: Using the mb_ereg_replace() Function
The mb_ereg_replace() function in PHP can be used to remove whitespace from the beginning and end of a string. This function is particularly useful for handling multibyte character encodings, ensuring that the string is processed correctly regardless of the character set.
Example
<?php
// Declare a string with whitespace at the beginning and end
$string = " Hello World! ";
$trimmedString = mb_ereg_replace('^\s+|\s+$', '', $string);
// Output the result
echo $trimmedString;
?>
Output
Hello World!