how to remove multiple slashes in URI with 'PREG' or 'HTACCESS'

后端 未结 5 2090
滥情空心
滥情空心 2021-01-04 21:51

how to remove multiple slashes in URI with \'PREG\' or \'HTACCESS\'

site.com/edition/new/// -> site.com/edition/new/


site.com/edition///new/ -> site.co

相关标签:
5条回答
  • 2021-01-04 22:24

    Edit: Ha I read this question as "without preg" oh well :3

    function removeabunchofslashes($url){
      $explode = explode('://',$url);
      while(strpos($explode[1],'//'))
        $explode[1] = str_replace('//','/',$explode[1]);
      return implode('://',$explode);
    }
    
    echo removeabunchofslashes('http://www.site.com/edition////new///');
    
    0 讨论(0)
  • 2021-01-04 22:28

    using the plus symbol + in regex means the occurrence of one or more of the previous character. So we can add it in a preg_replace to replace the occurrence of one or more / by just one of them

       $url =  "site.com/edition/new///";
    
    $newUrl = preg_replace('/(\/+)/','/',$url);
    
    // now it should be replace with the correct single forward slash
    echo $newUrl
    
    0 讨论(0)
  • 2021-01-04 22:30

    http://domain.com/test/test/ > http://domain.com/test/test

    # Strip trailing slash(es) from uri
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.+?)[/]+$ $1 [NC,R,L]
    

    http://domain.com//test//test// > http://domain.com/test/test/

    # Merge multiple slashes in uri
    RewriteCond %{THE_REQUEST} ^[A-Z]+\ //*(.+)//+(.*)\ HTTP
    RewriteRule ^ /%1/%2 [R,L]
    RewriteCond %{THE_REQUEST} ^[A-Z]+\ //+(.*)\ HTTP
    RewriteRule ^ /%1 [R,L]
    

    Change R to R=301 if everything works fine after testing...

    Does anyone know how to preserve double slashes in query using above method?

    (For example: /test//test//?test=test//test > /test/test/?test=test//test)

    0 讨论(0)
  • 2021-01-04 22:34
    $url = 'http://www.abc.com/def/git//ss';
    $url = preg_replace('/([^:])(\/{2,})/', '$1/', $url);
    // output http://www.abc.com/def/git/ss
    
    $url = 'https://www.abc.com/def/git//ss';
    $url = preg_replace('/([^:])(\/{2,})/', '$1/', $url);
    // output https://www.abc.com/def/git/ss
    
    0 讨论(0)
  • 2021-01-04 22:49

    Simple, check this example :

    $url ="http://portal.lojav1.local//Settings////messages";
    echo str_replace(':/','://', trim(preg_replace('/\/+/', '/', $url), '/'));
    

    output :

    http://portal.lojav1.local/Settings/messages
    
    0 讨论(0)
提交回复
热议问题