开发者

replace the username and password from a url using preg_replace

开发者 https://www.devze.com 2023-03-06 23:04 出处:网络
how can you replace the username and password from a URL with \'...\' example ftp://name:pass@example.com/file.mov

how can you replace the username and password from a URL with '...'

example

ftp://name:pass@example.com/file.mov becomes ftp://...@example.com/file.mov

http://name开发者_JS百科:pass@example.com/file.mov becomes http://...@example.com/file.mov


Use parse_url() it has everything you need.

Example:

$url = 'ftp://name:pass@example.com/file.mov';
print_r(parse_url($url));

Output:

Array
(
    [scheme] => ftp
    [host] => example.com
    [user] => name
    [pass] => pass
    [path] => /file.mov
    [query] => 
    [fragment] => 
)

You can then build your new URL like this:

$url    = parse_url($url);
$newUrl = $url['scheme'].'://'.$url['host'].$url['path'].$url['query'].$url['fragment'];


Not the most efficient nor the most reliable way, but I wanted to try to do it with a regex. Turns out that it's quite easy:

preg_replace("#(?<=://)[^:@]+(:[^@]+)?(?=@)#","...",$url);


Probably the best way to do this is with parse_url: get the components, modify them, then build them back into a string.

$parts = parse_url('ftp://name:pass@example.com/file.mov');
$parts['user'] = 'newusername';
$parts['pass'] = 'newpassword';

$url = $parts['scheme'] . '://' . 
       (isset($parts['user']) ? $parts['user'] : '') . 
       (isset($parts['pass']) ? ':' . $parts['pass'] . '@' : '') . 
       $parts['host'] .
       $parts['path'] . 
       (isset($parts['query']) ? '?' . $parts['query'] : '') . 
       (isset($parts['fragment']) ? '#' . $parts['fragment'] : '');


replace the regular expression

([a-z]+://)[^@]*(@.*)

with the following backreferences

$1$2

so I guess in php it would look something like

preg_replace ("([a-z]+://)[^@]*(@.*)", "$1$2", $yourstring)
0

精彩评论

暂无评论...
验证码 换一张
取 消