Sen123
Sen123

Reputation: 97

remove front and last of the character of a string in php

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?

Upvotes: 0

Views: 224

Answers (3)

Chirag Jain
Chirag Jain

Reputation: 1387

<?php
function remove($word){
$result = substr($word, 1, -1);
return $result;
}
$word = 'HELLO';
$results = remove($word);
echo $results;

?>

Demo

Upvotes: 0

Bluetree
Bluetree

Reputation: 11

try this code.

   function remove_char(string $s){
      if(strlen($s) > 1){
          return substr($s, 1, -1);
      }
      return false;
   }

Upvotes: 1

Adi Prasetyo
Adi Prasetyo

Reputation: 1042

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);
}

Upvotes: 1

Related Questions