开发者

Finding Subdomain And Adding WWW with REGEX

开发者 https://www.devze.com 2023-02-04 05:20 出处:网络
I\'m validating and adding http (or http开发者_运维知识库s) to my URL variable with this code :

I'm validating and adding http (or http开发者_运维知识库s) to my URL variable with this code :

$url = preg_replace("/[^A-Za-z0-9-\/\.\:]/", "", trim($url));
$url = preg_replace('%^(?!https?://).*%', 'http://$0', $url);

But this isn't enough for me. I need one more step , too . I have to check subdomain. If there isn't any subdomain add www.

For example if there isn't any subdomain and (after this 2 preg_replace()) if $url is : http://example.com , convert to http://WWW.example.com. If $url is : http://www.example.com, don't touch.

(with preg_replace please)

IN SUMMARY if $url hasn't subdomain and www , add www .


may be easier to use php's url parser.

http://www.php.net/manual/en/function.parse-url.php


I got this:

$url = 'http://teknoblogo.com';
$host = parse_url($url, PHP_URL_HOST);
$arr = explode('.', $host);

echo http_build_url($url,
    array(
        'host' => !preg_match('/^www\d*\.$/i', $arr[0]) && count($arr) <= 2 ? 'www.' . $host : $host
    )
);

See also:

  • parse_url()
  • http_build_url()


Without TLD lookup tables, the only way I imagine you can do this is if you know your domain already:

$domain = 'example.com';

$url = preg_replace('~^(https?://)(' . preg_quote($domain, '~') . ')(.*)~i', '$1www.$2$3');
0

精彩评论

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