问题描述
很抱歉,如果这对作为堆栈溢出问题的挑战来说太少了,但我对正则表达式还是陌生的.
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.
我的问题是,下面所有示例返回字符串"token"的正则表达式是什么?
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
- (在编辑后添加)
- domain.com
- domain.com/
- 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/
我试图在preg_replace函数内部使用,以便从$ _SERVER ['SERVER_NAME']变量中找出当前页面的子域.
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.
预先感谢您,tilt
Thank you in advance,titel
编辑说明:对不起,混乱和自负,我编辑了我的问题,最初的意思是我忘了写了,因为它完全可以在没有任何子域的情况下工作-在这种情况下它将返回空字符串或NULL
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
推荐答案
preg_replace('/^(?:([^\.]+)\.)?domain\.com$/', '\1', $_SERVER['SERVER_NAME'])
编辑:以下内容为您提供了什么?
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 />";
?>
这篇关于在PHP中使用正则表达式找出子域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!