In this article, you will understand more than one way to remove the last char from the PHP string.
Anyway, the question is how to use PHP to remove the last character from the string. In the following sections, I am going to cover 2 ways that are doing that.
Using the Substr Replace Function
The substr_replace is a predefined PHP function used to replace a part from text with another one.
It takes four parameters, such as
- the $string variable is for the PHP string sentence
- the $replace variable is for the needed string that would replace on the old part.
- $offset to select the started index from left to right and if it take a negative value that means it will start from the right.
- And the final is an optional parameter with $length.
Let's take an example.
<?php
$string = "My Office behind the Door..";
$replace = "";
$offset = -1;
echo substr_replace( $string, $replace, $offset );
// The output: My Office behind the Door.
?>
As you saw, the value was printed is the full sentence but deleted the last dot from the string. But how to replace a word instead of another word.
To do that, you have to select the first char from the target word and know the index number and then set a new value with the $replace variable
Let's see that with the following code.
<?php
$string = "Hello World";
$replace = "Petter";
$offset = 6; // is the begining of the Wolrd word.
echo substr_replace( $string, $replace, $offset );
// The output: Hello Peter
?>
Remove the Last Character using the Mb Substr Function
The mb_substr is only getting a part from the target string. That means, we need only to return the need part without the last Character.
Let's see that in the following PHP code.
<?php
$string = "Am I Doing That ?";
echo mb_substr( $string , 0, -1 ); // Am I Doing That
?>
Wrapping Up
In this article, you understood what is substr_replace function and how to use it to replace a string from a sentence. Also you learned how to remove the last char from a PHP string using two predefined PHP functions.
To learn more ways, follow the Flat Coding tutorils
Thanks for reading, stay tuned for my next tutorials
Top comments (0)