Regular expression, replace multiple slashes with only one

耗尽温柔 提交于 2020-01-03 11:25:08

问题


It seems like an easy problem to solve, but It's not as easy as it seems. I have this string in PHP:

////%postname%/

This is a URL and I never want more than one slash in a row. I never want to remove the slashes completely.

This is how it should look like:

/%postname%/

Because the structure could look different I need a clever preg replace regexp, I think. It need to work with URLS like this:

////%postname%//mytest/test///testing

which should be converted to this:

/%postname%/mytest/test/testing

回答1:


Here you go:

$str = preg_replace('~/+~', '/', $str);

Or:

$str = preg_replace('~//+~', '/', $str);

Or even:

$str = preg_replace('~/{2,}~', '/', $str);

A simple str_replace() will also do the trick (if there are no more than two consecutive slashes):

$str = str_replace('//', '/', $str);



回答2:


Try:

echo preg_replace('#/{2,}#', '/', '////%postname%//mytest/test///testing');



回答3:


function drop_multiple_slashes($str)
{
  if(strpos($str,'//')!==false)
  {
     return drop_multiple_slashes(str_replace('//','/',$str));
  }
  return $str;
}

that's using str_replace




回答4:


Late but all these methods will remove http:// slashes too, but this.

function to_single_slashes($input) {
    return preg_replace('~(^|[^:])//+~', '\\1/', $input);
}

# out: http://localhost/lorem-ipsum/123/456/
print to_single_slashes('http:///////localhost////lorem-ipsum/123/////456/');



回答5:


My solution:

while (strlen($uri) > 1 && $uri[0] === '/' && $uri[1] === '/') {
    $uri = substr($uri, 1);
}



回答6:


echo str_replace('//', '/', $str);


来源:https://stackoverflow.com/questions/2217759/regular-expression-replace-multiple-slashes-with-only-one

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!