How to Remove Last 2, 3, 4, 5, 7 Characters of a String in PHP?

By Hardik Savani May 14, 2024 Category : PHP

Hey,

This is a short guide on how to remove last two characters of a string in php. This article will give you a simple example of php remove last 4 characters of string. I’m going to show you about php remove last 3 characters of string. you will learn php delete last 5 characters of string.

In this example, we will use substr() function to remove last 2, 3, 4, 5 and 7 characters from string in php. so, let's see the following example code:

index.php

<?php

$string = "Welcome to ItSolutionstuff.com";

$last2Char = substr($string, 0, -2);

var_dump($last2Char);

$last3Char = substr($string, 0, -3);

var_dump($last3Char);

$last4Char = substr($string, 0, -4);

var_dump($last4Char);

$last5Char = substr($string, 0, -5);

var_dump($last5Char);

$last7Char = substr($string, 0, -7);

var_dump($last7Char);

?>

Output:

string(28) "Welcome to ItSolutionstuff.c"

string(27) "Welcome to ItSolutionstuff."

string(26) "Welcome to ItSolutionstuff"

string(25) "Welcome to ItSolutionstuf"

string(23) "Welcome to ItSolutionst"

I hope it can help you...

Tags :
Shares