replace the username and password from a url using preg_replace

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

example

ftp://name:[email protected]/file.mov becomes ftp://[email protected]/file.mov

http://name:[email protected]/file.mov becomes http://[email protected]/file.mov

--------------Solutions-------------

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("#(?<=://)[^:@]+(:[^@]+)?([email protected])#","...",$url);

Use parse_url() it has everything you need.

Example:

$url = 'ftp://name:[email protected]/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'];

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:[email protected]/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)

Category:php Time:2011-05-19 Views:1
Tags: php regex

Related post

Copyright (C) pcaskme.com, All Rights Reserved.

processed in 0.970 (s). 13 q(s)