1

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?

6 Answers 6

8

Or you can use parse_url:

parse_url($domain, PHP_URL_HOST);
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

Hi, thanks. That worked. :) Is there anyway to also remove anything after .com ?
If you want to extract just the domain, then, the best thing is to use parse_url(), as suggested by Mickael.
0

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.

Comments

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

Comments

0
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.

Comments

0

simple regex:

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

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.