How to remove the last character of a string in PHP?

Member

by viviane , in category: PHP , 2 years ago

How to remove the last character of a string in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 2 years ago

@viviane You can use substr() function in PHP to remove the last character of any string in PHP, here is example:


1
2
3
4
5
6
7
8
<?php

$text = "Test string";

$text = substr($text, 0, -1);

// Output: Test strin
print_r($text);


by hortense_donnelly , a year ago

@viviane 

To remove the last character of a string in PHP, you can use the substr() function to extract a substring from the original string, starting from the first character and ending at the second to last character. Here's an example:

1
2
3
$string = "Hello World!";
$modifiedString = substr($string, 0, -1);
echo $modifiedString; // Output: "Hello World"


In this example, the substr() function takes three arguments: the original string, the starting index (which is 0 for the first character), and the length of the substring to extract (which is -1 to exclude the last character). The resulting substring is assigned to the $modifiedString variable and then printed out using the echo statement.


Alternatively, you can also use the mb_substr() function to handle multi-byte characters:

1
2
3
$string = "Hello World!";
$modifiedString = mb_substr($string, 0, -1);
echo $modifiedString; // Output: "Hello World"


Both of these approaches will remove the last character of the string and return the modified string as a result.