Q:

How to remove last character from string using PHP?

belongs to collection: PHP Programming Exercises

0

In this exercise, you will learn how to remove the last character from a string using PHP.

This is a very common PHP interview question and generally asked in programming interviews, 'how to remove the last character from string in PHP'. Or, during the development process, you may come across a situation where you need to eliminate the last character from a string. This exercise shows you different ways to achieve the process from the given string. You can use any of the following methods to remove the last character from the string.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Method1: using substr() function

This function is used to return a part of a string or substring from a string, starting from a given position.

Syntax - 

substr(string,start,length)

The string is the required parameter. It should be a string datatype, start specifies where to start in the string and length is an optional parameter. If it is positive, the returned string contains the length characters from the beginning, and if it is negative, the returned string contains the length characters from the end of the string.

Example - 

<?php 

$str1 = "Good Morning!";

echo "Original string: " . $str1 . "<br/>";
echo "Updated string: " . substr($str1, 0, -1) . "<br/>";
?>

 Output - 

Original string: Good Morning!
Updated string: Good Morning

Method 2: using mb_substr() function

It returns the part of the string. It performs a multi-byte safe substr() operation based on the number of characters. The position is counted from the beginning of the string.

Syntax - 

mb_substr ( string $str , int $start [, int $length = NULL [, string $encoding = mb_internal_encoding() ]] )

Here, the $str is the string to extract the substring from, $start specifies where to start in the string, $length specifies the maximum number of characters to use from $str.

Example - 

<?php 

$str1 = "Good Morning!";

echo "Original string: " . $str1 . "<br/>";
echo "Updated string: " . mb_substr($str1, 0, -1) . "<br/>";
?>

 Output - 

Original string: Good Morning!
Updated string: Good Morning

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

PHP Programming Exercises

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Write a PHP program to reverse a string without pr... >>
<< How to insert image in database using PHP...