Trim only the first and last occurrence of a character in a string (PHP)

This is something that I could hack together, but I wondered if anyone had a clean solution to my problem. Something that I throw together will not necessarily be very brief or fast!

I have a string like ///hello/world/// . I need to remove only the first and last slashes, none of the others, so I get a line like this //hello/world// .

PHP trim not quite right: executing trim($string, '/') will return hello/world .

It should be noted that there will not necessarily be any slashes at the beginning or end of a line. Here are some examples of what I would like to do with different lines:

 ///hello/world/// > //hello/world// /hello/world/// > hello/world// hello/world/ > hello/world 

Thanks in advance for your help!

+2
string php trim
Sep 30 '10 at 19:56
source share
6 answers

The first thing, in my opinion:

 if ($string[0] == '/') $string = substr($string,1); if ($string[strlen($string)-1] == '/') $string = substr($string,0,strlen($string)-1); 
+8
Sep 30 2018-10-10T00:
source share

I think this is what you are looking for:

 preg_replace('/\/(\/*[^\/]*?\/*)\//', '\1', $text); 
0
Sep 30 '10 at 20:05
source share

Different regex using backlinks:

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

This has the advantage that if you want to use characters other than / you can make it more legible. It also causes the character / to start and end the line and allow / appear inside the line. Finally, it only removes the symbol from the very beginning, if there is a symbol at the end, and vice versa.

0
Sep 30 '10 at 20:11
source share

Another implementation:

 function otrim($str, $charlist) { return preg_replace(sprintf('~^%s|%s$~', preg_quote($charlist, '~')), '', $str); } 
0
01 Oct '10 at 7:44
source share

It was over 6 years ago, but I give an answer, one way or another:

 function trimOnce($value) { $offset = 0; $length = null; if(mb_substr($value,0,1) === '/') { $offset = 1; } if(mb_substr($value,-1) === '/') { $length = -1; } return mb_substr($value,$offset,$length); } 
0
May 12 '17 at 2:57 a.m.
source share

This function acts as an official trim, except that it is trimmed only once.

 function trim_once($text, $c) { $c = preg_quote($c); return preg_replace("#^([$c])?(.*?)([$c])?$#", '$2', $text); } 
 php > echo trim_once("||1|2|3|*", "*|"); |1|2|3| php > echo trim_once("//|1|2|3/", "/"); /|1|2|3 
0
May 26 '19 at 5:57
source share



All Articles