Page 1 of 1
how to remove special characters from url
Posted: Sun Sep 13, 2009 9:25 am
by gimpact
Hello,
I am new to php and I really dont know how to get this done.
I am making a members site. Each users will given a unique url, some thing like this http://<user name>.domain.com . I dont want to let user have url like this http://<user name>.<user name 2>.domain.com . That is basically, I want to remove characters such as ".", ",", "/", "\", "!" .. and so on.
I did make some basic searches but I have no idea, how to go about this. I will really appreciate is some one shows me a tutorial or some thing, that would help me.
Thank you,
Re: how to remove special characters from url
Posted: Sun Sep 13, 2009 10:27 am
by superdezign
Code: Select all
$invalidCharacters = array('.', ',');
if (strpos($username, $invalidCharacters) !== FALSE) {
// Invalid username
}
It is smarter to create a whitelist instead of a blacklist when it comes to usernames, though.
Re: how to remove special characters from url
Posted: Sun Sep 13, 2009 10:27 am
by jackpf
If you want to replace everything that isn't alphanumeric or a dash (which I think is what valid domain/subdomains can consist of), you could try this:
Code: Select all
$str = preg_replace('/[^A-Za-z0-9\-]/', null, $str);
EDIT
superdezign, just saw your reply...yeah, you could do that as well. Depends if you want to replace invalid characters, or notify your user that there are invalid characters.
Re: how to remove special characters from url
Posted: Sun Sep 13, 2009 10:33 am
by Eric!
You could also just pick the characters you want to remove
Code: Select all
$input=preg_replace("/[:.,!\/\\\\]/i","",$input);
This removes the characters
http://cnn.com!and,this\junk
to this:
httpcnncomandthisjunk
If you want to replace them with spaces
Code: Select all
$input=preg_replace("/[:.,!\/\\\\]/i"," ",$input);
Changes
http://cnn.com!and,this\junk
to this:
http cnn com and this junk
Re: how to remove special characters from url
Posted: Sun Sep 13, 2009 10:40 am
by lipun4u
in naive way...
Code: Select all
<?php
$url="http://amit.raju.asit.domain.com";
$part = str_ireplace("http://","",$url);
$part = str_ireplace(".domain.com","",$part);
$spc_arr = array(".", ",", "/", "!" );
for($i=0; $i<count(spc_arr); $i++) {
$part=str_ireplace($spc_arr[$i], "", $part);
}
$url = "http://" . $part . ".domain.com";
echo ($url);
?>

Re: how to remove special characters from url
Posted: Sun Sep 13, 2009 10:41 am
by jackpf
I prefer my example

No offense.
Re: how to remove special characters from url
Posted: Sun Sep 13, 2009 10:43 am
by superdezign
jackpf wrote:
I prefer my example

No offense.
preg_replace() is cleaner, but str_replace() is faster.

Re: how to remove special characters from url
Posted: Sun Sep 13, 2009 11:09 am
by jackpf
True...but that for() loop probably slows stuff down though.
@lipun4u
You do know str_replace() takes arrays as args right?
