Jacob
Jacob

Reputation: 11

Remove http from variable

I have a variable, such as this:

$domain = "http://test.com"

I need to use preg_replace or str_place to get the variable like this:

$domain = "test.com"

I have tried using the following, but they do not work.

1) $domain = preg_replace('; ((ftp|https?)://|www3?\.).+? ;', ' ', $domain);
2) $domain = preg_replace(';\b((ftp|https?)://|www3?\.).+?\b;', ' ', $domain);

Any suggestions?

Upvotes: 1

Views: 553

Answers (6)

Gabriel Anderson
Gabriel Anderson

Reputation: 1391

simple regex:

preg_replace('~^(?:f|ht)tps?://~i','', 'https://www.site.com.br');

Upvotes: 0

Mickael
Mickael

Reputation: 81

Or you can use parse_url:

parse_url($domain, PHP_URL_HOST);

Upvotes: 8

Andreas
Andreas

Reputation: 2266

preg_match('/^[a-z]+:[/][/](.+)$/', $domain, $matches);
echo($matches[1]);

Should be what you are looking for, should give you everything after the protocol... http://domain.com/test becomes "domain.com/test". However, it doesn't care about the protocol, if you only want to support specific protocols such as HTTP and FTP, then use this instead:

preg_match('/^(http|ftp):[/][/](.+)$/', $domain, $matches);

If you only want the domain though, or similar parts of the URI, I'd recommend PHP's parse_url() instead. It does all the hard work for you and does it the proper way. Depending on your needs, I would probably recommend you use it anyway and just put it all back together instead.

Upvotes: 0

Mark Lalor
Mark Lalor

Reputation: 7887

$domain = ltrim($domain, "http://");

Upvotes: 3

genesis
genesis

Reputation: 50966

preg_replace('~(https://|http://|ftp://)~',, '', $domain);

Upvotes: 0

Andreas
Andreas

Reputation: 5335

Did you try the str_replace?

$domain = "http://test.com"
$domain = str_replace('http://','',$domain);

You regular expressions probably don't find a match for the pattern.

Upvotes: 0

Related Questions