> 백엔드 개발 > PHP 튜토리얼 > PHP의 트림()

PHP의 트림()

WBOY
풀어 주다: 2024-08-29 12:49:18
원래의
991명이 탐색했습니다.

trim() is one of the in-built functions of PHP whose purpose is to trim the white spaces and also other predefined characters from both the left and right sides of a string. Hence it is very useful in various scenarios such as:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

  • To clean up input given by the user like the text field values which are submitted.
  • Remove line break characters at the end of the line which is not required.
  • To parse or to make sure that the string is in the required format before it is passed on to another program.

Syntax with Parameters

Following is a syntax with parameters:

Syntax:

trim ( string $str [, string $character_mask = " \t\n\r\0\x0B" ] ) : string
로그인 후 복사

As shown above, input parameters for this trim function include the input string which will be trimmed of its whitespaces from the beginning and the end of its string $str. The second parameter in the syntax is optional and is used to define explicitly what characters should be trimmed exactly.

Hence without the second parameter, the trim function trims the below parameters by default:

  • ” ” (ASCII 32 (0x20)) which is a normal space character.
  • “\t” (ASCII 9 (0x09)) which is a tab character
  • “\n” (ASCII 10 (0x0A)) which represents a new line character.
  • “\r” (ASCII 13 (0x0D)) which is a carriage return character.
  • “\0” (ASCII 0 (0x00)) which is called the NULL byte.
  • “\x0B” (ASCII 11 (0x0B)) which represents a vertical tab.

Parameters Required:

  • str: This is the input string that will be trimmed of whitespaces.
  • character_mask: This is an optional field that can also be specified using this parameter. All the characters mentioned inside the braces will be trimmed. With this, we can also specify a wide range of characters.
  • Return values: Outputs a trimmed string.

Types of trim() in PHP

There are 3 different types of trim() functions that can be used for the below-mentioned purposes:

  • trim(): This is a normal one and can be used to trim from both the beginning and end of a string.
  • ltrim(): This is used to trim characters from the beginning of the input string
  • rtrim(): This is used to trim characters from the end of the input string.

Examples of trim() in PHP

Given below are the examples of trim() in PHP:

Example #1 – To remove the newline character.

Code:

<?php
$str = "\n\nDemo text!\n\n";
echo "Trim: " . ($str);
?>
로그인 후 복사

Output:

PHP의 트림()

In the above example, we are showcasing to see the output without the use of the trim() function. In the string assigned we are displaying newlines as part of the sentence for testing purposes. The same thing can be seen in the output.

<?php
$str = "\n\nDemo text!\n\n";
echo "Trim: " . trim($str);
?>
로그인 후 복사

Output:

PHP의 트림()

The above example displays a basic program for the usability of trim() function. Here $str is the variable to which the required string or a sentence is to be declared. After using the trim function as seen in the output it trims all the \n present in the input string and displays the string.

Example #2 – To remove tab character.

Code:

<?php
$str1=" Just an example";
$str_new=trim($str1,"\t");
//echo $str_new;
var_dump($str_new);
?>
로그인 후 복사

Output:

PHP의 트림()

In the above example, we are using the trim function to remove tab (“\t”) character by explicitly specifying the character in the second parameter of the trim function as seen. First, we are assigning the required string to a parameter called str1, and then using another parameter $str_new to append a tab at the end of the $str1. Simultaneously trim function is used which removes this tab character from the end of the string.

When we try the same code by removing the trim function we can see that an extra tab will get printed at the end of the string as we have appended it in a $str_new parameter. Hence trim functionality is verified.

Example #3 – To remove blank space characters.

Code:

<?php
$str = "
No blank space
";
// Displays "No blank space"
echo trim( $str );
?>
로그인 후 복사

Output:

PHP의 트림()

In the above example, we can see that the input string has a lot of blank spaces at its beginning. Hence to remove this we are using the trim function. As seen in the output, all the blank spaces from the beginning have been trimmed out and the proper input string is displayed. Also please note that only the whitespaces between the start and end of the string are trimmed and not the ones in between the sentence. Like the spaces in between “Example” and “to” are still the same.

Example #4 – To remove more than one special character.

Code:

<?php
$str = "\r\r Removing both characters \n\n";
// Displays " Removing both characters "
echo trim( $str, "\r\n" );
?>
로그인 후 복사

Output:

PHP의 트림()

In the above example, we can see that the input string has 2 special characters “\n” and “\r”. Hence, we will use the optional second parameter in the trim function to explicitly specify a range of characters (“\n” and “\r” in this case) that needs to be trimmed. As we can see in the output, the mentioned characters are trimmed.

Example #5 – To display trimming of numbers as well.

Code:

<?php
$str = "123 Just an example 456";
// Displays "Just an example"
echo trim( $str, " 0..9" );
?>
로그인 후 복사

Output:

PHP의 트림()

By using the trim() function we can also trim the numbers by specifying it in the second parameter list. It also allows us the use of dot notation using which if we specify as “0..9” the function removes all numbers in the input string ranging from 0 to 9. Hence in the above example using the above method it will trim the numbers “123” and “456” from the beginning and the end of the input string respectively.

Example #6 – To trim using rtrim() and ltrim()

Code:

<?php
$str = " Example for ltrim ";
// Displays "Example for ltrim "
echo ltrim( $str );
echo "\n";
$str = "452 Example for rtrim 456";
// Displays "123 Example for rtrim"
echo rtrim( $str, " 0..9" );
?>
로그인 후 복사

Output:

PHP의 트림()

As seen in the above example when ltrim is used, it only trims the extra spaces at the starting of the string. Similarly, when rtrim is used by specifying to trim numbers from 0 to 9, it only trims the numbers from the end of the string.

Conclusion

In this article, we have gone through in-depth the usage of trim(), ltrim(), and rtrim() functions which are basically used to remove the characters which are not required from a string. We have also seen how to specify our own whitespace character for trimming.

위 내용은 PHP의 트림()의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
php
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿