cppit
cppit

Reputation: 4564

find all subdomains in a string using php

hello here is my html :

<div>
hello.domain.com
holla.domain.com
stack.domain.com
overflow.domain.com </div>

I want to return an array with : hello, holla, stack,overflow

then I have this https://hello.domain.com/c/mark?lang=fr I want to return the value : mark I know it should be done with regular expressions. As long as I know how to do it regular expression or not it will be good. thank you

Upvotes: 1

Views: 155

Answers (4)

zx81
zx81

Reputation: 41848

Part 1: Subdomains

$regex = '~\w+(?=\.domain\.com)~i';
preg_match_all($regex, $yourstring, $matches);
print_r($matches[0]);

See the matches in the regex demo.

Match Array:

[0] => hello
[1] => holla
[2] => stack
[3] => overflow

Explanation

  • The i modifier makes it case-insensitive
  • \w+ matches letters, digits or underscores (our match)
  • The lookahead (?=\.domain\.com) asserts that it is followed by .domain.com

Part 2: Substring

$regex = '~https://hello\.domain\.com/c/\K[^\s#?]+(?=\?)~';
if (preg_match($regex, $yourstring, $m)) {
    $thematch = $m[0];
    } 
else { // no match...
     }

See the match in the regex demo.

Explanation

  • https://hello\.domain\.com/c/ matches https://hello.domain.com/c/
  • The \K tells the engine to drop what was matched so far from the final match it returns
  • [^\s#?]+ matches any chars that are not a white-space char, ? or # url fragment marker
  • The lookahead (?=\?) asserts that it is followed by a ?

Upvotes: 3

mhawke
mhawke

Reputation: 87134

For the second part of your question (extract part of a URL) others have answered with a highly specific regex solution. More generally what you are trying to do is parse a URL for which there already exists the parse_url() function. You will find the following more flexible and applicable to other URLs:

php > $url = 'https://hello.domain.com/c/mark?lang=fr';
php > $urlpath = parse_url($url, PHP_URL_PATH);
php > print $urlpath ."\n";
/c/mark
php > print basename($urlpath) . "\n";
mark
php > $url = 'ftp://some.where.com.au/abcd/efg/wow?lang=id&q=blah';
php > print basename(parse_url($url, PHP_URL_PATH)) . "\n";

This assumes that you are after the last part of the URL path, but you could use explode("/", $urlpath) to access other components in the path.

Upvotes: 0

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89629

About the second part of your question, you can use the parse_url function:

$yourURL = 'https://hello.domain.com/c/mark?lang=fr';

$result = end(explode('/', parse_url($yourURL, PHP_URL_PATH)));

Upvotes: 0

jjonesdesign
jjonesdesign

Reputation: 399

Although I am not sure where you are trying to take this.

$input = 'somthing.domain.com';

$string = trim($input, '.domain.com');

may help you.

Upvotes: 0

Related Questions