3

Possible Duplicate:
remove last character from string

I want to delete the last character in the text..

For example

My string: example text
Second : example tex

How?

Community
  • 1
  • 1
Yusuf
  • 63
  • 1
  • 6
  • 2
    Please search before asking - http://www.google.com/search?q=remove+last+character+of+string+php – Tom Walters Jul 09 '11 at 18:03
  • 1
    i searched but i cant find this :( – Yusuf Jul 09 '11 at 18:08
  • 3
    @Tom [Please don't direct people to Google pages](http://meta.stackexchange.com/questions/5280/embrace-the-non-googlers) and [please don't use link shorteners](http://meta.stackexchange.com/questions/64450/ban-url-shorting-services). – lonesomeday Jul 09 '11 at 18:09
  • 1
    The 2nd result: PHP.net - http://php.net/manual/en/function.substr.php - under the "length" parameter heading the first line of code describes + solves your problem. – Tom Walters Jul 09 '11 at 18:10
  • @lonesomeday I was simply pointing out the laziness of the user, and didn't want to crowd the comment, but point taken. – Tom Walters Jul 09 '11 at 18:12
  • 1
    @BilltheLizard Please remove the duplicate marking. The [other question](http://stackoverflow.com/q/5592994/318765) means "all specific characters" and not only "the last". You can see this by which answer was accepted. The question itself is wrong and should be corrected. – mgutt Apr 02 '15 at 09:55

4 Answers4

9

Use substr

$text = 'Example Text';
$text = substr($text, 0, -1)

substr takes three arguments, the original text, start and length, it return the substring from the original text starting at start with the given length. If length is negative, that number of characters will be excluded from the string, that's why whe are using the value -1, to exclude the last char from the string.

albertein
  • 26,396
  • 5
  • 54
  • 57
2

Use substr, which gets a substring of the original string:

$str = 'example text';
$newStr = substr($str, 0, -1); // "example text"

0 means "start at the beginning", -1 means "go until one character before the end".

lonesomeday
  • 233,373
  • 50
  • 316
  • 318
1

use this

substr($string, 0, -1);
genesis
  • 50,477
  • 20
  • 96
  • 125
0

Simple and straight to the point

 
$str[strlen($str) - 1] = ''; 

Does your stuff.

Strings are in actuality an array of characters in php. You can therefore set the last index to an empty string. Using unset() would have been nicer but php doesn't allow unsetting string indices.

frostymarvelous
  • 2,786
  • 32
  • 43