0

I have a URL where I pass the base auth within the URL, example:

https://user:[email protected]

What would be a regex to remove everything between the last / up to the @?

Example:

https://user:[email protected]

Would become:

https://dev.google.com

I tried some regex but my knowledge is still basic for this subject.

I'll use a PHP function to do a replace.

3
  • Which programming language? Do not comment, just add a proper tag. Commented Sep 26, 2018 at 17:43
  • 1
    Is there a reason you're using a regexp instead of parse_url()? Commented Sep 26, 2018 at 17:45
  • @Barmar no reason at all, I'm actually new to php so I'm not familiar with parse_url() yet, I'll take a look on this, thanks for the suggestion! Commented Sep 26, 2018 at 17:50

2 Answers 2

1
preg_replace('#/[^/]*@#', '/', $url);

Breakdown:

  • / matches a slash
  • [^/]* matches a sequence of non-slash characters
  • @ matches the @ character.

So this matches everything from a / to the next @, with no / between them. Then it's replaced with just the slash.

However, it would probably be better to use parse_url() rather than ad hoc parsing with a regexp.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks it solved my problem, I'll accept the answer as soon as it let me :)
And what about url's like example.com/@username/profile?
@Philipp That's why I recommended using a URL parser rather than ad hoc parsing, since it will deal with corner cases better.
1

Using parse_url() does the job:

$url = 'https://user:[email protected]';
$scheme = parse_url($url, PHP_URL_SCHEME);
$host = parse_url($url, PHP_URL_HOST);
print $scheme."://".$host;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.