简体   繁体   English

PHP RegEx字符串替换

[英]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. 我最近写了一个JavaScript RegExp来清理前端的数据,现在我需要对PHP后端执行完全相同的操作,但是有一段时间我没有在PHP中工作过。 Below is the javascript RegExp, can someone please help me convert this to PHP? 以下是JavaScript RegExp,有人可以帮我将其转换为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. 因此,总而言之,我想全局删除所有非法字符,删除空格并大写该变量,因为该变量将用于在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). 老实说,我认为您最好指定好字符,而不是尝试查找所有坏字符(毕竟,您忘记了很多非ASCII字符)。 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: 您可以这样调整JS:

var illegalChars = /[^a-z0-9_]/gi;
var siteSuggest = $(this).val().replace(new RegExp(illegalChars), '').toUpperCase();

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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