0

I've recently written a javascript RegExp to cleanse my data at the front end, I now need to do exactly the same for my PHP back end but not having worked in PHP for a while I'm having trouble. Below is the javascript RegExp, can someone please help me convert this to PHP?

var illegalChars = /[\(\)\<\>\,\;\:\.\~\@\#\$\!\%\^\&\*\'\?\(\)\+\=\{\}\`\\\/\"\[\]]/gi;  
var siteSuggest = $(this).val().toUpperCase().split(' ').join('').replace(new RegExp(illegalChars), "");

So, in summary, I want to remove all of the illegal characters globally, remove spaces & capitalize the variable as the variable will be used to create a database or table in sql.

2
  • I think you do not have to escape every character and you have () two times in your expression. Commented Jun 2, 2010 at 16:08
  • Cheers Felix, i'll look into that one Commented Jun 2, 2010 at 20:09

2 Answers 2

10

Honestly, I think you'd be better off specifying good characters rather than trying to find all bad characters (after all, there's plenty of non-ASCII characters you forgot about). I'd do something like:

$regex = '#[^a-z0-9_]#i';
$val = preg_replace($regex, '', $val);
$val = strtoupper($val);

This regex will have allowable characters as all alpha, numerics and _. If there's more you want, just add them to the character class. There's no need to split on a space, since the regex will match spaces (The ^ at the start of the character class is a negation)...

You can adjust your JS like this:

var illegalChars = /[^a-z0-9_]/gi;
var siteSuggest = $(this).val().replace(new RegExp(illegalChars), '').toUpperCase();
Sign up to request clarification or add additional context in comments.

4 Comments

This. Also, replace with a space instead of nothing, or the result could look messy.
@Matt \W (or the negation of \w) will be identical to the character class I used in an English locale. If you're using a non-english locale, it can include other characters (which may or may not be allowable or desirable). I also spelled it out, so that it's easy to see how to add additional characters. But if those are the only ones that you want (And you're only ever going to use an English locale), you can just replace the entire character class with \W
@ircmaxell Thank you,your solution looks good but it doesn't seem to replace the spaces which is a requirement.
@ircmaxell....sorry, you're quite correct....thank you so much for your assistance, works like a charm!
0

$illegal_chars = array(' ', ';', '~', '@', ...);
strtoupper(str_replace($illegal_chars, '', $value));

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.