Regular expression, replace multiple slashes with

2019-06-19 21:05发布

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

6条回答
地球回转人心会变
2楼-- · 2019-06-19 21:28

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/');
查看更多
迷人小祖宗
3楼-- · 2019-06-19 21:31

Try:

echo preg_replace('#/{2,}#', '/', '////%postname%//mytest/test///testing');
查看更多
【Aperson】
4楼-- · 2019-06-19 21:31
function drop_multiple_slashes($str)
{
  if(strpos($str,'//')!==false)
  {
     return drop_multiple_slashes(str_replace('//','/',$str));
  }
  return $str;
}

that's using str_replace

查看更多
相关推荐>>
5楼-- · 2019-06-19 21:43

My solution:

while (strlen($uri) > 1 && $uri[0] === '/' && $uri[1] === '/') {
    $uri = substr($uri, 1);
}
查看更多
霸刀☆藐视天下
6楼-- · 2019-06-19 21:49
echo str_replace('//', '/', $str);
查看更多
We Are One
7楼-- · 2019-06-19 21:52

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);
查看更多
登录 后发表回答