user123
user123

Reputation: 5407

php regex to alow slash in string

Here is my regex to exclude special character other then allowing few like (-,%,:,@). I want to allow / also but getting issue

 return preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%:@&-]/s', '', $string);

this works fine for listed special character, but

 return preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%\\:&-]/s', '', $string); 

does not filter l chracter to.

Here is the link to test:

http://ideone.com/WxR0ka

where it does not allow \\ in url. I want to dispaly URL as usual

Upvotes: 0

Views: 40

Answers (1)

anubhava
anubhava

Reputation: 784928

You're making a mistake in entering http:// by http:\\ also your regex needs to include / in exclusion list. This should work:

function clean($string) {
   // Replaces all spaces with hyphens.
   $string = str_replace(' ', '-', $string);
   // Removes special chars.
   return preg_replace('~[^\w %\[\].()%\\:@&/-]~', '', $string);
}

$d =  clean("this was http://nice readlly n'ice 'test for@me to") ;
echo $d; // this-was-http://nice-readlly-nice-test-for@me-to

Working Demo

Upvotes: 3

Related Questions