views:

56

answers:

4

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!

+4  A: 

First thing on my mind:

if ($string[0] == '/') $string = substr($string,1);
if ($string[strlen($string)-1] == '/') $string = substr($string,0,strlen($string)-1);
Parkyprg
I believe the substring method would probably run a lot quicker than the regular expression.
Kevin
This is very roughly what I'd throw together myself.. I would like to avoid regex if it's going to be slower, are there any stats to back up the speed of simple string manipulation functions vs regex?
Rowan
@Rowan: no, there are no such stats, as it's _very_ dependant on the actual manipulation going on, sometimes regexes do win. The only way to tell is to benchmark it for your expected strings, and even then I'd say using the one over the other based on performance is probably micro-optimalisation.
Wrikken
@Kevin only if there are thousands of such lines. And good programmer should avoid such numbers.
Col. Shrapnel
Awesome, thanks very much. I've been warned off micro-optimisation before :)
Rowan
A: 

I think this is what you you are looking for:

preg_replace('/\/(\/*[^\/]*?\/*)\//', '\1', $text);
harpax
Argh, can't you just switch delimiters? `#/(/*[^/]*?/*)/#`. However, you forget to anchor it:`#^/(/*[^/]*?/*)$/#`, and for effectiveness sake you might as well use `preg_replace('#(^/|/$)#','',$text);`
Wrikken
The difference between `/\/(\/*[^\/]*?\/*)\//` and `#(^/|/$)#` is why people are quick to write off regex as unreadable.
Daniel Vandersluis
A: 

A different regex, using backreferences:

preg_replace('/^(\/?)(.*)\1$/','\2',$text);

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.

lonesomeday
A: 

Yet another implementation:

function otrim($str, $charlist)
{
 return preg_replace(sprintf('~^%s|%s$~', preg_quote($charlist, '~')), '', $str);
}
Alix Axel