
So the beginning of the retrieval is 4 characters from the end of the string rather than the beginning. Accordingly, using -1 as parameter, makes the last character to be removed and -2 is deleting the last two characters and with passing -4, we are removing of the last four characters from our input string. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

It works well when both when $string contains '/' and it does not contain '/' (it does not modify $string in this case). In this case the value of position of the beginning of the retrieval is negative. The negative values ensure that it is counted from behind and the specified number of characters will be removed. Solution #3, using preg_replace(): $string = ' echo(preg_replace('#/*$#', '/', $string)) ĭrawbacks: none. Wanting the ability to return back the original string unaltered if search char/string not found. Removing from left or right side of string (first or last occurrence). Need to check the number of items in the array produced by explode(). Using strripos/strrpos when character/string not found in string. While working with PHP, it is often necessary to remove characters from strings. The Second Option is Substrreplace Function. There is a 4-year-old girl in rural Arkansas who is learning to ride a camouflage-patterned four-wheeler alongside her cousins.

#PHP TRIM LAST 4 CHARACTERS HOW TO#
$array = '' // empty the last componentĮcho(implode('/', $array)) // join the pieces backĭrawback (for both versions): if $string does not contain '/', explode() produces an array containing a single value and the rest of the code produces either '/' (the first piece of code) or an empty string (the second). How to Remove the Last Character from a String in PHP. Solution #2, using explode() + implode(): $string = ' $array = explode('/', $string) Īrray_pop($array) // ignore the returned value, we don't need itĮcho(implode('/', $array).'/') // join the pieces back, add the last '/'Īlternatively, instead of array_pop($array) we can make the last component empty and there is no need to add an extra '/' at the end: $string = ' $array = explode('/', $string) Need to check the value returned by strrpos() first. Solution #1, using substr() + strrpos(): $string = ' $pos = strrpos($string, '/') įunction strrpos() finds the position of the last occurrence of / in the string, substr() extracts the required substring.ĭrawback: if $string does not contain '/', strrpos() returns FALSE and substr() does not return what we want.
