View Full Version : str_replace regex

11-05-2009, 01: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:


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


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

Please a little help?

11-05-2009, 02: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);

Should be:

[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.

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

Thanks m8!

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

11-05-2009, 02:40 AM
Got it.