0

A question about php.

If I have variable named $string that contains the word "Testing" I would like the php code to delete the first and last character. (So the output would be "estin"). I've tried multiple functions for example str_replace and substr but so far I've only managed to delete only the first or only the last character.

I don't know how to delete both the first and last character.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136

6 Answers6

12
<?php
$str = 'Testing';
$result = substr($str, 1, -1);
echo $result; // estin

the result of the code: http://codepad.org/RLbw4azA

read more about: substr


function: substr can receive 3 parameters:

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

If length is given and is negative, then that many characters will be omitted from the end of string (after the start position has been calculated when a start is negative). If start denotes the position of this truncation or beyond, false will be returned.

srain
  • 8,944
  • 6
  • 30
  • 42
4

use preg_replace

$string = preg_replace('/^.|.$/','',$string);
Nasir Iqbal
  • 909
  • 7
  • 24
3
$str = "Testing";
echo $str = substr($str,1,-1);
M Shahzad Khan
  • 935
  • 1
  • 9
  • 22
3

Have you tried this:

$string = substr($string, 1, -1);
Bhushan
  • 6,151
  • 13
  • 58
  • 91
2

try substr($string, 1, -1). It will help

david
  • 3,225
  • 9
  • 30
  • 43
1

$str = 'ABCDEFGH';

echo $result = substr($str, 1, -1);

//output will be show the BCDEFG

Patel
  • 543
  • 4
  • 20