php - 使用正则表达式检查 MySQL 查询值中的 '%' 字符

标签 php mysql regex

我想检查 MySQL 查询的值是否包含 % 字符(可以出现多次),但不包含转义的 \%

所以它应该匹配:

  • '%测试'
  • '%test\%'
  • 'test\\%' - 应该匹配,因为它是转义 \ 而不是 %
  • '%test\%%'
  • '\%test%test\%'

但不是:

  • '测试\%'
  • '\%test\%'
  • '\%test\%test\%'

我不擅长正则表达式,有人可以帮助我吗?

提前致谢。

编辑:
我正在尝试创建一个 PHP 库来从数组生成 SQL 查询,也许生成的查询将主要在 MySQL 上使用。
因此,正则表达式过滤过程将在 PHP 中进行。

抱歉,我忘了提及这一点。

谢谢

最佳答案

检查 PHP 代码:

unset($str1,$str2,$str3,$str4,$str5,$str6,$str7);

$str1 = '%100'; 
$str2 = '%100\%';
$str3 = "100\\\\%";
$str4 = "%100\\%%";
$str5 = '100\%';
$str6 = "100\\\\\\\\%";
$str7 = "100\\\\\\%";
$str8 = "100\\\\\\\\\\\\%";
$str9 = "100\\\\\\\\\\\\\\%";

$reg_exp=  '/^%|[^\x5C]%|[^\x5C](\x5C\x5C)+%/';

echo $str1.' = '.preg_match($reg_exp, $str1).'<br />';
echo $str2.' = '.preg_match($reg_exp, $str2).'<br />';
echo $str3.' = '.preg_match($reg_exp, $str3).'<br />';
echo $str4.' = '.preg_match($reg_exp, $str4).'<br />';
echo $str5.' = '.preg_match($reg_exp, $str5).'<br />';
echo $str6.' = '.preg_match($reg_exp, $str6).'<br />';
echo $str7.' = '.preg_match($reg_exp, $str7).'<br />';
echo $str8.' = '.preg_match($reg_exp, $str8).'<br />';
echo $str9.' = '.preg_match($reg_exp, $str9).'<br />';

http://ideone.com/Bgq5bV

关于php - 使用正则表达式检查 MySQL 查询值中的 '%' 字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13488107/

相关文章:

php - JOIN 中重复的 SQL 结果 - Codeigniter

php - mysql子查询计数位置和分组依据

python - 正则表达式替换 Python

mysql - 如何更改 WAMP 上运行的 MySQL 中的只读变量

Java 替换 xml 中的单词

.net core webapi路由属性正则表达式与/

php - Laravel 查询破坏了我的变量

php - 在 codeigniter 选择查询中获取空数组

mysql - 转换Mysql中的查询

返回唯一关联的 MySQL 语句