This is something I could hack together, but I wondered if anybody had a clean solution to my problem. Something that I throw together wont necessarily be very concise or speedy!
I have a string like this ///hello/world///
. I need to strip only the first and last slash, none of the others, so that I get a string like this //hello/world//
.
PHP's trim
isn't quite right right: performing trim($string, '/')
will return hello/world
.
One thing to note is that the string won't necessarily have any slashes at the beginning or end. Here are a few examples of what I would like to happen to different strings:
///hello/world/// > //hello/world//
/hello/world/// > hello/world//
hello/world/ > hello/world
Thanks in advance for any help!
It has been more than 6 years old ago, but I'm giving may answer anyway:
I think this is what you you are looking for:
A different regex, using backreferences:
This has the advantage that, should you want to use characters other than /, you could do so more legibly. It also forces the / character to begin and end the string, and allows / to appear within the string. Finally, it only removes the character from the beginning if there is a character at the end as well, and vice versa.
First thing on my mind:
Yet another implementation:
This function acts as the official trim, except that it only trims once.