0

My goal is to create a function that removes the first and last characters of a string in php.

My code:

function remove_char(string $s): string {
    $len = strlen($s);
    return substr($s,1,$len-2);
}

This not past the codewar code test. Can anyone tell me why it is not correct?

Sen123
  • 97
  • 1
  • 8
  • 2
    Works [**perfectly for me**](https://3v4l.org/VJEBZ). Please ensure you have provided a [**minimal, complete, and verifiable example**](http://stackoverflow.com/help/mcve) of the problem. Note that the explicit `string` type will only be valid in PHP 7 though. – Obsidian Age Nov 06 '17 at 01:04
  • 2
    Possible duplicate of [Delete first 3 characters and last 3 characters from String PHP](https://stackoverflow.com/questions/7045618/delete-first-3-characters-and-last-3-characters-from-string-php) – Chirag Jain Nov 06 '17 at 01:50
  • Questions without any errors are off-topic on StackOverflow. Perhaps you would like your working code to be reviewed at CodeReview. – mickmackusa Nov 06 '17 at 04:16

3 Answers3

1

The built in function substr is accepting negative value, when you use negative value it affect readability. You can also give the function name better and clearer name like so:

function modify_string(string $s): string {
  return substr($s, 1, -1);
}
Adi Prasetyo
  • 1,006
  • 1
  • 15
  • 41
  • If you also want to control the offset at the beginning or at the end: `function modify_string($string, $offset_b = 1, $offset_e = 1) { return substr($s, $offset_b, 0 - $offset_e); }` – cram2208 Nov 06 '17 at 02:20
1

try this code.

   function remove_char(string $s){
      if(strlen($s) > 1){
          return substr($s, 1, -1);
      }
      return false;
   }
Bluetree
  • 11
  • 1
  • Code-only answers do very little to educate future readers. Always endeavor to include some manner of explanation regarding why/how it is the solution. – mickmackusa Nov 06 '17 at 04:08
0
<?php
function remove($word){
$result = substr($word, 1, -1);
return $result;
}
$word = 'HELLO';
$results = remove($word);
echo $results;

?>

Demo

Chirag Jain
  • 1,367
  • 1
  • 11
  • 27
  • Code-only answers do very little to educate future readers. Always endeavor to include some manner of explanation regarding why/how it is the solution. – mickmackusa Nov 06 '17 at 04:09