简体   繁体   中英

Regular expression, replace multiple slashes with only one

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

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

尝试:

echo preg_replace('#/{2,}#', '/', '////%postname%//mytest/test///testing');
function drop_multiple_slashes($str)
{
  if(strpos($str,'//')!==false)
  {
     return drop_multiple_slashes(str_replace('//','/',$str));
  }
  return $str;
}

that's using str_replace

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/');

My solution:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM