代码之家  ›  专栏  ›  技术社区  ›  Rowan

只修剪字符串(php)中字符的第一次和最后一次出现

  •  2
  • Rowan  · 技术社区  · 14 年前

    这是我可以拼凑起来的东西,但我想知道是否有人能彻底解决我的问题。我拼凑起来的东西不一定很简洁或者很快!

    我有一根这样的绳子 ///hello/world/// . 我只需要去掉第一个和最后一个斜杠,其他的都不需要,这样我就能得到这样的一个字符串。 //hello/world//

    PHP的 trim 不太对:表演 trim($string, '/') 会回来的 hello/world .

    需要注意的一点是,字符串的开头或结尾不一定有任何斜线。以下是我希望在不同字符串上发生的一些示例:

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

    提前感谢您的帮助!

    5 回复  |  直到 8 年前
        1
  •  8
  •   CristiC jason.zissman    14 年前

    我想的第一件事是:

    if ($string[0] == '/') $string = substr($string,1);
    if ($string[strlen($string)-1] == '/') $string = substr($string,0,strlen($string)-1);
    
        2
  •  0
  •   harpax    14 年前

    我想这就是你想要的:

    preg_replace('/\/(\/*[^\/]*?\/*)\//', '\1', $text);
    
        3
  •  0
  •   lonesomeday    14 年前

    另一个regex,使用backreferences:

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

    这样做的好处是,如果您想使用除/以外的字符,可以更清楚地做到这一点。它还强制/字符开始和结束字符串,并允许/出现在字符串中。最后,它只从一开始就删除字符,如果在末尾也有一个字符,反之亦然。

        4
  •  0
  •   Alix Axel    14 年前

    还有一个实现:

    function otrim($str, $charlist)
    {
     return preg_replace(sprintf('~^%s|%s$~', preg_quote($charlist, '~')), '', $str);
    }
    
        5
  •  0
  •   Pedro Amaral Couto    8 年前

    它已经6年多了,但我还是给了梅答案:

    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);
    }