Web Analytics

PHP trim() Function

String Function PHP 4+

The trim() function removes whitespace (or other characters) from both ends of a string.

Syntax

trim(string $string, string $characters = " \n\r\t\v\x00"): string

Parameters

ParameterTypeDescription
$stringstringThe string to trim
$charactersstringCharacters to remove (optional)

Return Value

Returns the trimmed string.

Try It Online

Output
Click Run to execute your code

More Examples

Basic Whitespace Removal

<?php
$str = "  Hello World  ";
echo "[" . trim($str) . "]";
// "[Hello World]"
?>

Left/Right Trim

<?php
$str = "  Hello  ";
echo ltrim($str);  // "Hello  " (left only)
echo rtrim($str);  // "  Hello" (right only)
?>

Custom Characters

<?php
$str = "###Hello###";
echo trim($str, "#");  // "Hello"
?>
Tip: Always trim user input before storing or comparing to avoid whitespace issues.

Common Use Cases

  • Cleaning form input
  • Normalizing strings for comparison
  • Removing BOM characters
  • Processing file content

Related Functions

  • ltrim() - Trim left side only
  • rtrim() - Trim right side only
  • str_replace() - Replace characters