简体   繁体   中英

PHP RegEx string Replace

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.

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();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM