0

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

1
  • What is your expected output? Commented Apr 20, 2014 at 8:02

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.