Follow
Follow

How to remove white space from a string in PHP

We can use the PHP trim() function to remove whitespace including non-breaking spaces, newlines, and tabs from the start and end of the string. It will not remove whitespace occurs within the middle of the string.

If you need to remove whitespace only from the start of a string, you must use the ltrim() function in PHP.

If you need to remove whitespace only from the end of a string, you should use the rtrim() function in PHP.

These functions will remove the following whitespace characters:

  • Space character (” “)
  • Tab character (“t”)
  • Vertical tab character (“v”)
  • Newline character (“n”)
  • Carriage return character (“r”)
  • Null-byte character (“x0B”)
<?php
$str1 = '    Welcome to PHP Tutorials ';
echo strlen($str1); // Outputs: 29

$trim_str = trim($str1);
echo strlen($trim_str); // Outputs: 24
?>
Newsletter
Join Design Community
Get the latest updates, creative tips, and exclusive resources straight to your inbox. Let’s explore the future of design and innovation together.