Find subdomain using regex in PHP

Sorry if this is too small to be suitable as a stack overflow issue, but I'm a little used to regular expressions.

My question is: what is a regular expression that returns the string “token” for all the examples below?

  • token.domain.com
  • token.domain.com/
  • token.domain.com/index.php
  • token.domain.com/folder/index.php
  • token.domain.com/folder/subfolder
  • token.domain.com/folder/subfolder/index.php
  • (added after editing)
  • domain.com
  • domain.com/

I am trying to use the preg_replace function inside to find out the subdomain of the current page from the variable $ _SERVER ['SERVER_NAME'].

Thanks in advance, Titel

: sebnow, , , , , - - , NULL

+3
4
preg_replace('/^(?:([^\.]+)\.)?domain\.com$/', '\1', $_SERVER['SERVER_NAME'])

: :

<?php
    echo preg_replace('/^(?:([^\.]+)\.)?domain\.com$/', '\1', "sean.domain.com") . "<br />";
    echo preg_replace('/^(?:([^\.]+)\.)?domain\.com$/', '\1', "titel.domain.com") . "<br />";
    echo preg_replace('/^(?:([^\.]+)\.)?domain\.com$/', '\1', "domain.com") . "<br />";
?>
+4

() :

^([^.]+)\..*$

, . :

list($subdomain, $rest) = explode('.', $_SERVER['SERVER_NAME'], 2);
+3

preg_replace(), :

preg_replace('/\..*/', '', $_SERVER['SERVER_NAME'])
0
preg_match('@^([a-zA-Z0-9]*\.)?([a-zA-Z0-9]+)\.([a-zA-Z]{2,4})$@',$_SERVER["HTTP_HOST"], $matches);
0

Source: https://habr.com/ru/post/1703015/


All Articles