Home >Backend Development >PHP Problem >How to remove the last two characters of a string in php

How to remove the last two characters of a string in php

青灯夜游
青灯夜游Original
2022-07-27 21:13:093120browse

Two methods for php to remove the last two characters of a string: 1. Use the substr() function to intercept all characters except the last two characters from the head of the string. Just change the second character of the function. Set the first parameter to 0, and set the third parameter to "-2", the syntax is "substr(string,0,-2)". 2. Use the substr_replace() function to replace the last two characters of the string with the empty character "''". The syntax is "substr_replace(string,"",-2,2)".

How to remove the last two characters of a string in php

The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer

php remove strings Two methods for the last two characters

Method 1: Use the substr() function

The substr() function can be specified from the string Position to intercept a certain length of characters. This intercepted character can be called a "substring" or "substring"

You only need to use the substr() function to intercept the last two types from the head of the string. All characters of characters:

  • means setting the second parameter of the function to 0, and setting the third parameter to -2 will delete the last two characters.

<?php  
header("content-type:text/html;charset=utf-8");
$str = "Hello World!";
echo "原字符串:";
var_dump($str);
$newstr=substr($str,0,-2);
echo "去除后两个字符:";
var_dump($newstr);
?>

How to remove the last two characters of a string in php

Method 2: Use the substr_replace() function

The substr_replace() function is used to specify Starting at position, replace part of the string with another string.

Just use the substr_replace() function to replace the last two characters of the string with null characters:

  • Set the replacement value (second parameter) to the null character '', set the starting position (the third parameter) to -2 to delete the last two characters.

<?php  
header("content-type:text/html;charset=utf-8");
$str = "Hello";
echo "原字符串:";
var_dump($str);
$newstr=substr_replace($str,"",-2,2);
echo "去除后两个字符:";
var_dump($newstr);
?>

How to remove the last two characters of a string in php

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to remove the last two characters of a 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