Site icon Nabtron

How to remove last (few) characters of a string variable in PHP

If you are in a situation where you need to remove last few (one or two, or even three or so on) characters from a variable using php, then the solution is pretty much simple.

Simply use this function to remove any number of desired characters from your string (variable)

substr($your-variable,0,-1);

In the above function $your-variable is the variable that you want to be trimmed off and from which you want to exclude those alphabets or characters using php. 0 defines the first character from the left for the new variable and -1 defines the last (second last one in this case)

Example PHP remove last 3 characters from a string

So if you want to remove 3 characters from the end of php string variable, simply do this:

$my-variable = “Mr. Nabeel is greatest”;

$my-new-variable = substr($my-variable,0,-3);

echo $my-new-variable;

Upon echo, it will show : Mr. Nabeel is great instead of Mr. Nabeel is greatest.

Similarly if we use this php function as:

$my-variable = “Mr. Nabeel is greatest”;

$my-new-variable = substr($my-variable,4,-3);

echo $my-new-variable;

Now it will show only Nabeel is great trimming off four characters from the beginning and three from the end of the sentence string variable using php builtin substr function.

Exit mobile version