Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out subdomain using Regular Expression in PHP

Tags:

regex

php

pcre

Sorry if this is too little of a challenge to be suited as a stack overflow question, but I'm kind of new to Regular Expressions.

My question is, what is the regular expression that returns the string "token" for all the examples bellow?

  • 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 edit)
  • domain.com
  • domain.com/

Im trying to use inside an preg_replace function in order to find out the subdomain of the current page from the $_SERVER['SERVER_NAME'] variable.

Thank you in advance, titel

Edit note: Sorry chaos and sebnow , I edited my question, what I initially meant, but forgot to write, was that this would work without any subdomain at all - case in which it would return an empty sting or NULL


1 Answers

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

Edit: What does the following output for you:

<?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 />";
?>
like image 75
2 revsuser21926 Avatar answered Apr 21 '26 16:04

2 revsuser21926



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!