Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove three characters at the end of a string in PHP?

Tags:

string

php

People also ask

How do I remove the last 3 characters from a string?

slice() method to remove the last 3 characters from a string, e.g. const withoutLast3 = str. slice(0, -3); . The slice method will return a new string that doesn't contain the last 3 characters of the original string.

How can I remove part of a string in PHP?

The substr() and strpos() function is used to remove portion of string after certain character. strpos() function: This function is used to find the first occurrence position of a string inside another string. Function returns an integer value of position of first occurrence of string.

How can I remove multiple special characters from a string in PHP?

function clean($string) { $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens. return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars. }


Just do:

echo substr($string, 0, -3);

You don't need to use a strlen call, since, as noted in the substr documentation:

If length is given and is negative, then that many characters will be omitted from the end of string


<?php echo substr("abcabcabc", 0, -3); ?>

<?php echo substr($string, 0, strlen($string) - 3); ?>