Home >Backend Development >PHP Problem >How to delete characters at the end of string in php

How to delete characters at the end of string in php

醉折花枝作酒筹
醉折花枝作酒筹Original
2021-03-26 16:07:332931browse

We know that there are several ways to delete characters from a string. Today we will introduce three PHP functions to delete the last character of a string. Friends in need can refer to them.

How to delete characters at the end of string in php

Method 1: substr() function

substr()The function returns a part of the string.

The syntax is as follows:

 substr(string string, int start, int [length]);

Parameter explanation:

  • ##The first parameter: represents the original string;

  • The second parameter: represents where to start intercepting;

  • The third parameter: represents the length we need to intercept.

Example:

<?php
$str = "1,2,3,4,5,6"; 
$newstr = substr($str,0,strlen($str)-1); 
echo $newstr; 
?>

Result:

1,2,3,4,5,

You can see that the output result

$strThe last character is gone.

Method 2: substr_replace() function

substr_replace()The function replaces part of a string with another string.

Although it is a replacement function, it can achieve inserted deletion of characters.

The syntax is as follows:

substr_replace()(string string, int start, int [length]);

Parameter explanation:

  • The first parameter: represents the original string;

  • The second parameter: represents where to start deleting;

  • The third parameter: represents how many characters need to be deleted.

Example:

$email=&#39;peter@qq.com&#39;;
echo substr_replace($email,&#39;&#39;,11,1);

The output result is:


peter@qq.co

The last character m is deleted.


Method 3: rtrim() function

If the last character of the string is a blank character or a special character, you can use

rtrim( ) function, and we only need one parameter, but if the last character is not a blank character or a special character, we need to specify the deleted character.

Grammar:

string rtrim ( string $str [, string $character_mask ] )

Parameter explanation:

  • The first parameter: represents the original string;

  • The second parameter: represents the characters that need to be deleted.

Example:

<?php
    $email=&#39;peter@qq.com&#39;;
    echo rtrim($email,"m");
?>

The output result is:

peter@qq.co

Recommended learning: "

PHP Video Tutorial"

The above is the detailed content of How to delete characters at the end of string in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn