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
?>

Categorized in: