We're a place where coders share, stay up-to-date and grow their careers.
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 :/
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 :/