Hướng dẫn
Quảng cáo

Hàm trim() trong PHP

Hướng dẫn cách sử dụng hàm trim() trong lập trình PHP

Tác dụng của hàm trim()

The trim() function strips whitespace and other characters from the beginning and end of a string.

The following table summarizes the technical details of this function.

Return Value: Returns the trimmed string.
Version: PHP 4+

Syntax

The basic syntax of the trim() function is given with:

trim(string, strip_characters);

The following example shows the trim() function in action.

<?php
// Sample string
$str = "  Hello World! ";

// Removing whitespace
echo trim($str);
?>

Parameters

The trim() function accepts the following parameters.

Parameter Description
string Required. Specifies the string to be trimmed.
strip_characters

Optional. Specifies the list of all characters that you want to be stripped.

If this parameter is not specified, trim() will strip all the following characters:

  • " " - an ordinary space
  • "\t" - a tab
  • "\n" - a new line
  • "\r" - a carriage return
  • "\0" - the NULL-byte
  • "\v" - a vertical tab

More Examples

Here're some more examples showing how trim() function actually works:

In the following example only space, tab and newline characters from the beginning and end of the string will be removed. The characters inside the string will remain unchanged.

<?php
// Sample string
$str = "  \tHello\n World!\n ";

// Removing whitespace
echo trim($str);
?>

In the following example only space, plus, and minus are removed from both end of the string.

<?php
// Sample string
$str = "  ++\tHello World!--- ";

// Removing characters
echo trim($str, " +-");
?>

Bài viết này đã giúp ích cho bạn?

Bài viết mới

Advertisements