Practical Web Programming

Thursday, January 15, 2009

PHP: How to Delete the First and Last Character in a String

Using PHP's substr and strlen functions, you can delete the first and last character in a string. Here's the syntax of the functions from the PHP documentation website.

string substr  ( string $string  , int $start  [, int $length  ] )

int strlen ( string $string )

substr returns a part of a string, while strlen returns the length of a string. See below for the example.


$my_name = "Joel Badinas";
$str_length = strlen($my_name);

$no_first_char = substr($my_name, 1, $str_length);
$no_last_char = substr($my_name, 0, $str_lenght - 1);

print ("Original String : " . $my_name . "<br/>");
print ("No first character: " . $no_first_char . "<br/>");
print ("No last character: " . $no_last_char . "<br/>");


The above source code will display the following:

Original String : Joel Badinas
No first character: oel Badinas
No last character: Joel Badina


Recent Post