Want to improve this question? Add details and clarify the problem by editing this post.
开发者_StackOverflow中文版Closed 2 years ago.
Improve this questioni need to use preg_replace to replace two subdomain elements with a single element. my regex skills are virtually nonexistent. the urls are of the form:
user1.common.domain.org
user2.common.domain.org
something.common.domain.org
else.common.domain.org
and need to be replaced with:
newvalue.domain.org
preg_replace( '/[a-z0-9]+\.common/i' , 'newvalue' , $url );
Try this:
preg_replace("/.+?(domain.+?)/", "newvalue.$1", "user1.common.domain.org");
This problem might not be best-solved with a regular expression. Try using explode()
:
$exploded = explode('.', $hostname);
if( (count($exploded) == 4) and ($exploded[1] == 'common') )
{
$exploded[0] = 'newvalue';
unset($exploded[1]);
}
$hostname = implode('.', $exploded);
(where $hostname
is the hostname you are checking [e.g., $_SERVER['HTTP_HOST']
)
The above code assumes that you are looking for hostnames that match the pattern *.common.domain.org
, and that the hostname will always end with domain.org
.
This will work:
$sd = "user1.common.domain.org";
$sd = preg_replace('/.*?\.common\.(domain\.org)/i', 'newvalue.$1', $sd);
echo $sd ;
outputs newvalue.domain.org
try this code:
preg_replace('/\w+\.\w+(?=\.\w+\.\w+)/i', 'newvalue', 'user1.common.domain.org');
This would be more concise:
For host:
$newValue = 'newvalue';
$newHost = preg_replace("/^.+(?:\.common)(\.domain\.org)$/", "$newValue$1", $host);
replaces string staring with any character one or more times + ".common" + ".domain" to "newvalue.domain.org"
For url:
$newValue = 'newvalue';
$newUrl = preg_replace("/^(https?:\/\/).+(?:\.common)(\.domain\.org)$/", "$1$newValue$2", $url);
replaces string staring with "http://" or "https://" + any character one or more times + ".common" + ".domain" to "http://" or "https://" + "newvalue.domain.org"
This is only for if you can be sure it ends with domain.org:
preg_replace('/(?:.*?)\.(?:.*?)(\.domain\.org)/', $new_val."$1", $url);
精彩评论