PHP 正则表达式 - 匹配一个字符组,当该字符组中的一个不在字符串中时
PHP Regex - Matching one of a character group, when ONE of that character group is not in a string
我觉得我一直在用头撞砖墙。
我有一个看起来像这样的字符串:
$record['filenameGood'] = '49161_Comma_Dataphoria-Clickwork7Export{DATE:dmY}';
而且我想阻止包含任何受限字符的文件名。
但是...我正在为当前日期使用占位符,它看起来像 {DATE:Y-m-d}
,其中 Y-m-d
将插入到 php
的 date
函数中。
这部分我没问题,它只是确保字符串的其余部分不包含受限字符。
我正在测试的脚本如下所示:
// Matches one of " * : % $ / \ ' ?
$patternOne = '#["*:%$/\\'?]#';
// Desired: matches one of " * : % $ / \ ' ?, but ALLOWS {DATE:.*?}
$patternTwo = '#["*:%$/\\'?]#';
$record = [];
$record['filenameGood'] = '49161_Comma_Dataphoria-Clickwork7Export{DATE:dmY}';
$record['filenameBad'] = '49161_Comma_Dataphoria-Clickwork7:Export{DATE:dmY}';
var_dump(preg_match($patternTwo, $record['filenameGood']));
var_dump(preg_match($patternTwo, $record['filenameBad']));
当前输出为:
int(1)
int(1)
而我想要的输出是:
int(0) // Good string, contains : within {DATE:}
int(1) // Bad string, contains a : NOT within {DATE:}
我还需要一个像下面这样的字符串来匹配:
'49161_Comma_Dataphoria-Clickwork7Export{DATE:d:m:Y}'
我希望我已经解释得足够让你理解了!
您可以在 之后 字符 class:
使用负面回顾
$patternTwo = '#["*:%$/\\\'?](?<!{DATE:)#';
^^^^^^^^^^^
参见IDEONE demo。
这里,首先匹配字符class中的一个字符,但随后负向后视将检查:
前面是否没有{DATE
。如果是,则匹配失败。
我觉得我一直在用头撞砖墙。
我有一个看起来像这样的字符串:
$record['filenameGood'] = '49161_Comma_Dataphoria-Clickwork7Export{DATE:dmY}';
而且我想阻止包含任何受限字符的文件名。
但是...我正在为当前日期使用占位符,它看起来像 {DATE:Y-m-d}
,其中 Y-m-d
将插入到 php
的 date
函数中。
这部分我没问题,它只是确保字符串的其余部分不包含受限字符。
我正在测试的脚本如下所示:
// Matches one of " * : % $ / \ ' ?
$patternOne = '#["*:%$/\\'?]#';
// Desired: matches one of " * : % $ / \ ' ?, but ALLOWS {DATE:.*?}
$patternTwo = '#["*:%$/\\'?]#';
$record = [];
$record['filenameGood'] = '49161_Comma_Dataphoria-Clickwork7Export{DATE:dmY}';
$record['filenameBad'] = '49161_Comma_Dataphoria-Clickwork7:Export{DATE:dmY}';
var_dump(preg_match($patternTwo, $record['filenameGood']));
var_dump(preg_match($patternTwo, $record['filenameBad']));
当前输出为:
int(1)
int(1)
而我想要的输出是:
int(0) // Good string, contains : within {DATE:}
int(1) // Bad string, contains a : NOT within {DATE:}
我还需要一个像下面这样的字符串来匹配:
'49161_Comma_Dataphoria-Clickwork7Export{DATE:d:m:Y}'
我希望我已经解释得足够让你理解了!
您可以在 之后 字符 class:
使用负面回顾$patternTwo = '#["*:%$/\\\'?](?<!{DATE:)#';
^^^^^^^^^^^
参见IDEONE demo。
这里,首先匹配字符class中的一个字符,但随后负向后视将检查:
前面是否没有{DATE
。如果是,则匹配失败。