- Как вы удаляете имя домена из URL-адреса в php?
- PHP Удалить домен из URL [дубликат]
- PHP remove http, https, www and slashes from URL
- URL Decode
- Remove http:// from the URL
- Add http:// in the URL
- Remove http://, www., and slashes from the URL
- Shorthand
- 2 Responses Leave a Comment
- Join the Discussion. Cancel
- Search
- Latest Posts
- Categories
- Subscribe
- Privacy Overview
Как вы удаляете имя домена из URL-адреса в php?
Я ищу метод (или функцию), чтобы вырезать часть domain.ext любого URL-адреса, который был введен в функцию. Расширение домена может быть любым (.com, .co.uk, .nl, anywhatever), а URL, который загружается в него, может быть любым: от http://www.domain.com до www.domain.com/path /script.php?=whatever
Каков наилучший способ сделать это?
parse_url превращает URL-адрес в ассоциативный массив:
php > $foo = "http://www.example.com/foo/bar?hat=bowler&accessory=cane"; php > $blah = parse_url($foo); php > print_r($blah); Array ( [scheme] => http [host] => www.example.com [path] => /foo/bar [query] => hat=bowler&accessory=cane )
Вы можете использовать parse_url () для этого:
$url = 'http://www.example.com'; $domain = parse_url($url, PHP_URL_HOST);
В этом примере $ domain должен содержать example.com.
Вы также можете написать регулярное выражение, чтобы получить именно то, что вы хотите.
$pattern = '/\w+\..(?:\..)?(?:$|(?=\/))/i'; $url = 'http://www.example.com/foo/bar?hat=bowler&accessory=cane'; if (preg_match($pattern, $url, $matches) === 1)
Этот шаблон также учитывает такие домены, как «example.com.au».
Примечание. Я не обращался к соответствующему RFC.
Вот несколько простых функций для получения корневого домена (example.com) из обычного или длинного домена (test.sub.domain.com) или URL (http://www.example.com).
/** * Get root domain from full domain * @param string $domain */ public function getRootDomain($domain) < $domain = explode('.', $domain); $tld = array_pop($domain); $name = array_pop($domain); $domain = "$name.$tld"; return $domain; >/** * Get domain name from url * @param string $url */ public function getDomainFromUrl($url) < $domain = parse_url($url, PHP_URL_HOST); $domain = $this->getRootDomain($domain); return $domain; >
Скажем, мы вызываем dev.mysite.com, и мы хотим извлечь ‘mysite.com’
$requestedServerName = $_SERVER['SERVER_NAME']; // = dev.mysite.com $thisSite = explode('.', $requestedServerName); // site name now an array array_shift($thisSite); //chop off the first array entry eg 'dev' $thisSite = join('.', $thisSite); //join it back together with dots ;) echo $thisSite; //outputs 'mysite.com'
Работы с mysite.co.uk тоже должны работать везде 🙂
Я потратил некоторое время на размышления о том, имеет ли смысл использовать регулярное выражение для этого, но, в конце концов, я думаю, что нет.
Первое выражение reresxp firstresponder приблизилось к тому, чтобы убедить меня, что это лучший способ, но он не работает ни на чем, у которого отсутствует конечная косая черта (например, http://example.com ). Я исправил это следующим образом: ‘/\w+\..(?:\..)?(?=[\/\W])/i’ , но потом я понял который дважды соответствует URL-адресам, например « http://example.com/index.htm ». К сожалению. Это было бы не так уж плохо (просто используйте первый), но он также дважды повторяется примерно так: « http://abc.ed.fg.hij.kl.mn/ », а первое совпадение – t правильный. 🙁
Сотрудник предложил просто получить хост (через parse_url() ), а затем просто взять последние два или три бита массива ( split() on ‘.’). Два или три будут основаны на списке доменов, например «co.uk» и т. д. Составление этого списка становится сложной.
Существует только один правильный способ извлечения частей домена, это использование Public Suffix List (база данных TLD). Я рекомендую пакет TLDExtract , вот пример кода:
$extract = new LayerShifter\TLDExtract\Extract(); $result = $extract->parse('www.domain.com/path/script.php?=whatever'); $result->getSubdomain(); // will return (string) 'www' $result->getHostname(); // will return (string) 'domain' $result->getSuffix(); // will return (string) 'com'
PHP Удалить домен из URL [дубликат]
parse_url превращает URL в ассоциативный массив:
php > $foo = "http://www.example.com/foo/bar?hat=bowler&accessory=cane"; php > $blah = parse_url($foo); php > print_r($blah); Array ( [scheme] => http [host] => www.example.com [path] => /foo/bar [query] => hat=bowler&accessory=cane )
Какой был бы лучший способ лишить WWW. если он присутствует в домене. IM не хорошо с регулярным выражением. Непонятный способ, о котором я могу думать, — $ www_check = substr ($ domain, 0,4); if ($ www_check == & quot; www. & quot;)
Мне нравится взорваться на «www. & Quot; а затем использовать первый экземпляр в массиве. Как правило, это нормально. – Robert Elwell 7 October 2008 в 03:12
Тщательный Роберт, поскольку у многих URls нет перед ними WWW. ie images.google.com – gradbot 7 October 2008 в 03:22
Существует только один правильный способ извлечения частей домена, это использование Public Suffix List (база данных TLD). Я рекомендую пакет TLDExtract , вот пример кода:
$extract = new LayerShifter\TLDExtract\Extract(); $result = $extract->parse('www.domain.com/path/script.php?=whatever'); $result->getSubdomain(); // will return (string) 'www' $result->getHostname(); // will return (string) 'domain' $result->getSuffix(); // will return (string) 'com'
Вы можете использовать parse_url () , чтобы сделать это:
$url = 'http://www.example.com'; $domain = parse_url($url, PHP_URL_HOST);
В этом примере $ domain должен содержать example.com.
Примечание: второй аргумент для parse_url — это изобретение PHP5. Любой на PHP4 (обновите, пожалуйста, за любовь к Богу . ) нужно будет использовать способ Роберта Элвелла. – ceejayoz 6 October 2008 в 23:36
Вы также можете написать регулярное выражение, чтобы получить именно то, что вы хотите.
$pattern = '/\w+\..(?:\..)?(?:$|(?=\/))/i'; $url = 'http://www.example.com/foo/bar?hat=bowler&accessory=cane'; if (preg_match($pattern, $url, $matches) === 1)
Этот шаблон также учитывает такие домены, как «example.com.au».
Примечание. Я не обращался к соответствующему RFC.
Могу ли я использовать этот шаблон регулярного выражения на другом языке? – User 28 March 2014 в 21:26
Я потратил некоторое время на размышления о том, имеет ли смысл использовать регулярное выражение для этого, но, в конце концов, я думаю, что нет.
regexp firstresponder приблизился к тому, чтобы убедить меня, что это лучший способ, но он не работал ни на чем, у которого отсутствовала конечная косая черта (так http://example.com , для пример). Я исправил это следующим образом: ‘/\w+\..(?:\..)?(?=[\/\W])/i’ , но потом я понял, что соответствует двум URL-адресам, например « http://example.com/index.htm ». К сожалению. Это было бы не так уж плохо (просто используйте первый), но он также дважды совпадает с чем-то вроде этого: « http://abc.ed.fg.hij.kl.mn/ ‘ , и первое совпадение неверно. : (
Сотрудник предложил просто получить хост (через parse_url() ), а затем просто взять последние два или три бита массива ( split() на ‘.’). Два или три основываться на списке доменов, таких как «co.uk» и т. д. Составление этого списка становится трудным.
PHP remove http, https, www and slashes from URL
In this article, I show you how to PHP remove http, https, www and slashes from URL inputted. So when user data obtain and store into the database, before that we need to save proper URL. That is the reason we need to remove http, https and slashes from URL.
URL Decode
First of all, encoded URL string we need to decode. For example (+) are decoded to a space character.
Remove http:// from the URL
If you want to remove the only http:// from URL. you have use PHP preg_replace() function.
Add http:// in the URL
On the other hand, if you want to add http:// in URL, you have to use preg_match() function. First, you have to check http:// or https:// existed in URL. If yes then no need to http:// prepend otherwise you have to http:// prepend to URL.
// Output http://www.way2tutorial.com echo $input; ?>
Remove http://, www., and slashes from the URL
If we need only domain hostname and store that into out database then we need to remove http:// , www. , and slash(/) from URL. So for that, when need to use four functions.
- First is trim() function, use for remove all slash from the URL.
- Second is preg_match() function, check http:// or https:// existed in URL. If yes then no need to http:// prepend otherwise you have to http:// prepend to URL.
- Third is parse_url() function, to parse the URL.
- And last forth preg_replace() function to remove www. from URL because we need only hostname.
Array ( [scheme] => http [host] => www.way2tutorial.com [path] => /tutorial/ ) /tutorial/
$urlParts = parse_url($input); // Remove www. $domain_name = preg_replace('/^www\./', '', $urlParts['host']); // Output way2tutorial.com echo $domain_name; ?>
Shorthand
To all above in shorthand way you can do following.
That’s all. If any query or confusion, please write down comment on below comment section. Moreover, you can explore here other PHP related posts.
If you like our article, please consider buying a coffee for us.
Thanks for your support!
2 Responses Leave a Comment
Join the Discussion. Cancel
Search
Latest Posts
Categories
Subscribe
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies. However you may visit Cookie Settings to provide a controlled consent.
Privacy Overview
This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.