Removal method: 1. Use the rtrim() function, the syntax is "rtrim(string, character)"; 2. Use the chop() function, the syntax is "chop(string, character)"; 3. Use substr() function, syntax "substr(string,0,-n)", parameter n specifies the number of characters to be removed.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
Method 1: Use rtrim() function
<?php $str = "Hello World!"; echo $str . "<br>"; echo rtrim($str,"World!"); ?>
Output:
Hello World! Hello
Description:
rtrim() function from string Starting from the end, whitespace characters or other predefined characters are removed. The syntax is as follows:
rtrim(string,charlist)
Description | |
---|---|
string | Required. Specifies the string to check.|
charlist | Optional. Specifies which characters are removed from a string. If this parameter is omitted, all of the following characters are removed:
|
Method 2: Use chop() function
<?php $str = "Hello World"; echo $str . "<br>"; echo chop($str,"World"); ?>
Hello World Hello
Description:
chop() function removes blank characters or other predefined characters at the right end of the string. The syntax is as follows:chop(string,charlist)
Method 3: Use substr() function
<?php $str = "Hello World!"; echo $str . "<br>"; echo substr($str,0,-5); ?>
Hello World! Hello W
Instructions:
substr() function returns a part of a string. The syntax is as follows:substr(string,start,length)
Description | |
---|---|
Required. Specifies a part of the string to be returned. | |
Required. Specifies where in the string to begin. | Positive number - starts at the specified position in the string
|
Optional. Specifies the length of the string to be returned. The default is until the end of the string. | Positive number - Returns from the position of the start parameter
|
Recommended learning: "
PHP Video TutorialThe above is the detailed content of How to remove the last few characters of a string in php. For more information, please follow other related articles on the PHP Chinese website!