Jump to content

Archived

This topic is now archived and is closed to further replies.

brown2005

remove www from url

Recommended Posts

Try this:
[code=php:0]<?php

$string = "Here´s a ftp://mysite.com string  https://mysite.com with a link to www.somesite.com bla bla";

$string2 = preg_replace('/([a-z]+:\/\/|[a-z]+:\/\/?www.)([-a-z0-9_][-a-z0-9_\.]+\.[a-z]{2,4}(\/[-a-z0-9_\.%&+\/=&]+)?)/is', '\\2', $string);

// remove any left over instances of www.
$string2 = str_replace('www.', '', $string2);

echo $string2;

?>[/code]

Share this post


Link to post
Share on other sites
ok, here's a shorter version... might achieve what you're after.

[code=php:0]
<?php
$string = "Here´s a string  https://mysite.com with a link to www.somesite.com bla bla";
echo preg_replace('/(https?:\/\/)?(www\.)?([^\s]+)/', '\\3', $string);
?>
[/code]

Also, there's another problem with your code wildteen88.. what about if my domain's http://www.ilovethewww.com ?

What's going to happen then  ;)

Regards
Rich

Share this post


Link to post
Share on other sites
Here´s one that takes care of [color=blue]ftp://[/color], [color=blue]ftp.[/color], [color=blue]http://[/color], [color=blue]https://[/color] and [color=blue]www[/color]

[code=php:0]$string = "Here´s a ftp://mysite.com - ftp.mysite.com string and https://mysite.com with a
link to www.somesite.com and to http://www.anothersite.com bla bla.
Yet another link to http://mysite.com/somedir/mysite.html";

echo preg_replace('/(http(s)?:\/\/|ftp(:\/\/|\.))(www\.)?(.*?[^\s])/is', '\\5', $string);[/code]

Share this post


Link to post
Share on other sites
Nicklas... why the parenthesis arount the first 's'?

You don't want to match it, and it's not being user for alternation.

Surely [color=green][tt]https?[/tt][/color] says match [color=red][tt]http[/tt][/color] and an optional [color=red][tt]s[/tt][/color]

Regards
Rich

Share this post


Link to post
Share on other sites
Yeah, I know, but for some reason, the expression falls apart if I do it that way, if I put the optional [b]s[/b] in a subpattern, it works.
Anyways, here´s a small update, the previous regexp removed everything as it should, but left the [b]www[/b] untouched. this has now been fixed.

[code=php:0]$string = "Here's a ftp://mysite.com - ftp.mysite.com string and https://mysite.com with a
link to www.somesite.com and to http://www.anothersite.com bla bla.
Yet another link to http://mysite.com/somedir/mysite.html";

echo preg_replace('/((http(s)?:\/\/|ftp(:\/\/|\.)))?(www\.)?/is', '', $string);[/code]

Share this post


Link to post
Share on other sites
omg, i didnt know this would cause so much action.. lol.. i presume some of u want to use this yourselves...

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.