PHP
function remove_string_ends($str) { if (strlen($str) <= 2) { return null; } return substr($str, 1, -1); }
I like that substr trick with the -1, didn't think of that!
How about this one liner?
<?php function trimThis(string $str) { return (mb_strlen($str) <= 2) ? null : substr($str,1,-1); }
Use mb_string to support multibyte chars, such as Chinese
Also typehinted the argument, you never know...
This one is even shorter, possible only if the arg is typehinted tho
<?php function trimThis(string $str) { return substr($str,1,-1) ?: null; }
When the string is shorter than 2, substr returns false; when the length is 2, substr returns "".
In both cases it's false, the the return is null.
Edit: many typos, I'm on mobile :/
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
PHP
I like that substr trick with the -1, didn't think of that!
How about this one liner?
Use mb_string to support multibyte chars, such as Chinese
Also typehinted the argument, you never know...
This one is even shorter, possible only if the arg is typehinted tho
When the string is shorter than 2, substr returns false;
when the length is 2, substr returns "".
In both cases it's false, the the return is null.
Edit: many typos, I'm on mobile :/