我需要使用preg_replace用一个元素替换两个子域元素。我的正则表达式技能几乎不存在。网址的格式为:regex/preg_replace替换子域
user1.common.domain.org
user2.common.domain.org
something.common.domain.org
else.common.domain.org
,需要被替换:
newvalue.domain.org
我需要使用preg_replace用一个元素替换两个子域元素。我的正则表达式技能几乎不存在。网址的格式为:regex/preg_replace替换子域
user1.common.domain.org
user2.common.domain.org
something.common.domain.org
else.common.domain.org
,需要被替换:
newvalue.domain.org
preg_replace('/[a-z0-9]+\.common/i' , 'newvalue' , $url);
这并不能确保只有domain.org的值被取代......它会对字符串 – devyndraen 2011-06-15 18:10:55
中的[a-z0-9] + \ common中的任何内容起作用,它将替换“common.domain “与”newvalue“。即元素2和3,而不是元素1和2 – lcdservices 2011-06-15 18:11:41
@devy:提供一个例子,因为我不明白你的意思。键盘首选 – dynamic 2011-06-15 18:11:57
这仅仅是因为如果你可以肯定它domain.org结束:
preg_replace('/(?:.*?)\.(?:.*?)(\.domain\.org)/', $new_val."$1", $url);
试试这个:
preg_replace("/.+?(domain.+?)/", "newvalue.$1", "user1.common.domain.org");
这个问题可能不是用正则表达式最好解决的。尝试使用explode()
:
$exploded = explode('.', $hostname);
if((count($exploded) == 4) and ($exploded[1] == 'common'))
{
$exploded[0] = 'newvalue';
unset($exploded[1]);
}
$hostname = implode('.', $exploded);
(其中$hostname
是要检查的主机名[例如,$_SERVER['HTTP_HOST']
)
上面的代码假设你正在寻找匹配模式的*.common.domain.org
是主机名,并且该主机名将总是以domain.org
结尾。
这将工作:
$sd = "user1.common.domain.org";
$sd = preg_replace('/.*?\.common\.(domain\.org)/i', 'newvalue.$1', $sd);
echo $sd ;
输出newvalue.domain.org
+1 “我正则表达式的技能是根本不存在” :) – dynamic 2011-06-15 18:05:57
见http://meta.stackexchange.com/q/66377/164291 – 2011-09-16 13:21:58