DEV Community 👩‍💻👨‍💻

Discussion on: Daily Challenge #1 - String Peeler

claudioscatoli profile image
Claudio Scatoli • Edited on

I like that substr trick with the -1, didn't think of that!

How about this one liner?


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

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 :/