...

View Full Version : str_replace regex



ubh
11-05-2009, 12:59 AM
Ok I have a url http://www.something.com/lots/of/stuff/out/here/

I wan to use str_replace to remove everything after the .com leaving me with:

http://www.something.com

I just for the life of me cant remember the regex that I would use in conjunction with the str_replace to do such a thing.. stupid JS has me all confused cause with JS its

.replace(/.com(.*)/g,"");

but (.*) is nothing PHP will know what to do with.

Please a little help?

Fou-Lu
11-05-2009, 01:08 AM
.* is pcre pattern for any character any number of times. You need to use preg_replace if you want to use the pattern.
And you can use parse_url to do what you're looking to do much easier. It will actually work with any extension though, so you would need more code if you wanted it to be bound to only .com:


$inputUrl = 'http://www.something.com/lots/of/stuff/out/here/';
$aUrlParts = parse_url($inputUrl);
print_r($aUrlParts);

Should be:


Array
(
[scheme] => http
[host] => something
[user] =>
[pass] =>
[path] => /lots/of/stuff/out/here/
[query] =>
[fragment] =>
)

I believe every part is returned regardless of if its null or not.

Now that I think of it, it won't return empty parts. On top of that though, this won't work because it don't return the domain suffix.
So, you can use preg_replace if you want (the pattern you have will actually work), or you can look at using substr/substr_replace and strpos to replace after .com happens.

Actually, I think it does return the .com as a part of the host, the api is unclear if this is the situation, and I'm at work so I can't test this out.

ubh
11-05-2009, 01:14 AM
Fou-Lu you rock my friend always a huge helper!!

Thanks m8!

Fou-Lu
11-05-2009, 01:16 AM
np mate, hope you caught my last edit there. Methinks that will work fine.

ubh
11-05-2009, 01:40 AM
Got it.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum