Home > database >  How to redirect to new url if multiple slashes in URI?
How to redirect to new url if multiple slashes in URI?

Time:03-16

I am using str_replace() for removing extra slashes from the URL and creating new url but I don't know how to redirect it to a new URL if found multi slashes in the URL?

$url = 'http://www.example.com///about///';
$new_url = str_replace(':/','://', trim(preg_replace('/\/ /', '/', $url), '/'));
if($new_url)
{
  echo 'Yes found multi slashes redirect it to new URL;
}
else
{
  echo 'Not found multi slashes';
}

CodePudding user response:

This might be a little programmer tunnel vision, there is probably a better way to to do this, but if you're looking to redirect based on the URL not being the same:

$url = 'http://www.example.com///about///';
$new_url = str_replace(':/','://', trim(preg_replace('/\/ /', '/', $url), '/'));
if ($url !== $new_url) {
    header(sprintf('Location: %s', $new_url));
}

The header can't be resent so if you have some other print before this, it will be an error. I would remove the $_SERVER or a CONST that would contain base_url. There are a lot of questions for your intent with code because it's easier way to do depending on what you're trying to do.

  • Related