3

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

4 Answers 4

4
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 />";
?>
Sign up to request clarification or add additional context in comments.

2 Comments

:( unfortunately the solution you described does not seem to work in my case
It does work now, I guess I misspelled something while I was passing the script to use my actual domain. Anyways, thanks a lot. Constantin TOVISI
3

The following regex would capture any string before a full stop (the subdomain) and the rest of the domain:

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

I don't see the need for regex to do this though. It would be much easier to split by the full stop and get the first element:

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

Comments

0

If you want to use preg_replace(), then:

preg_replace('/\..*/', '', $_SERVER['SERVER_NAME'])

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.