Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use trim($string) to remove PHP’s documented default whitespace and control characters from both ends of a string. It leaves characters in the middle untouched.

Trim whitespace from both ends

The PHP Manual describes trim() as “Strip whitespace (or other characters) from the beginning and end of a string.” With no second argument, it removes these characters: ordinary space (0x20), tab (0x09), line feed (0x0A), carriage return (0x0D), NUL (0x00), and vertical tab (0x0B).

<?php
$name = "  Ada Lovelacet";
$clean = trim($name); // "Ada Lovelace"
?>

The string’s interior is not changed. For example, spaces between words remain in place.

Trim only the beginning or end

Choose the function according to which edge needs cleaning:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Function What it removes Example result
trim($string) Matching characters from both ends "Ada"
ltrim($string) Matching characters from the beginning only "Ada " from " Ada "
rtrim($string) Matching characters from the end only " Ada" from " Ada "

See the PHP Manual entries for ltrim() and rtrim().

<?php
$leftClean = ltrim("  Ada Lovelace  ");  // "Ada Lovelace  "
$rightClean = rtrim("  Ada Lovelace  "); // "  Ada Lovelace"
?>

Remove specific characters with a character mask

Pass a second argument to trim a different set of characters. It is a character mask: each listed character is eligible for removal at either edge, rather than the argument being treated as one literal substring.

<?php
$punctuationClean = trim("...hello...", "."); // "hello"
$clean = trim("Hello World", "Hdle");
?>

In the second example, PHP can remove any of H, d, l, or e as they occur at the edges. It does not look for the exact text Hdle. A mask can also use .. to specify an incrementing range; the PHP Manual shows "x00..x1F" for a range of control characters. Keep masks limited to the characters your input actually requires.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Do not assume every Unicode whitespace character is trimmed

PHP’s documented default is the specific character set listed above, not a promise to remove every character that might be considered whitespace in Unicode. If your input may contain a particular non-ASCII whitespace character, verify that character and your target PHP version before choosing a trimming approach.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.