WordPress Contact Form 7 正则表达式验证处理方式与在线正则表达式测试人员不同?

WordPress Contact Form 7 Regex validation handles differently than online regex testers?

WordPress 中使用 Contact Form 7 插件尝试验证输入 从“€ 5000”开始,步长为 5000。因此可能的输入为“€ 10.000”、“€ 15.000”、“€ 255000”等。

“2000 欧元”、“5050 欧元”等输入值应为 FALSE

我使用在线正则表达式测试器构建的表达式有效 (php)

/^[€]\s(1?[5]000|[1-9]{1}[5,0]{1,3}([0]{3,10}))$/

参见 工作示例 -> https://regex101.com/r/PvqlES/2

虽然它在 regex101 环境中工作,但当我在 functions.php 中将确切的正则表达式导入我的 WordPress 函数时,它没有按预期进行验证。

这是我写在 functions.php 底部的函数:

add_filter('wpcf7_validate_text*', 'validate_price', 20, 2);
add_filter('wpcf7_validate_text', 'validate_price', 20, 2);

function validate_price( $result, $tag ) {
    if( 'participationPrice' == $tag->name) {
        $participationPrice = isset( $_POST['participationPrice'] ) ? trim( $_POST['participationPrice'] ) : '';
        if (!preg_match("/^[€]\s(1?[5]000|[1-9]{1}[5,0]{1,3}([0]{3,10}))$/g", $participationPrice)){
            $result->invalidate( $tag, "Please provide a value similar to '€ 5000' with steps of 5000." );
        }
    }
 return $result;
}

这是 Contact Form 7 标签:

[text* participationPrice]

表单确实检查了验证,因为它显示了错误消息:

error message validates

问题:为什么在线正则表达式测试器可以正确验证,但一旦导入到 WordPress,它就无法正确验证。我只能假设正则表达式需要一些调整,以便 WordPress 可以理解它。我做错了什么/错过了什么?

测试 使用一个非常简单的正则表达式看它是否会通过:

/^[0-9]{0,1}$/

不过,此正则表达式确实按预期工作。

奖金,如果有更好的验证方法,比如输入必须被 5000 整除。那将是更好的验证方法,因为我确信当前的正则表达式有很多漏洞。

提前致谢!

您可以使用 '~€\s*\K\d+~u' 正则表达式从字符串中提取任何数字,然后使用简单的检查过滤结果数组是否可以除以 5000:

$s = "€ 5000\n€ 3000\n€ 10000\n€ 13000\n€ 20000\n\n€ 5000\n€ 3000\n€ 100000\n\n€ 13000\n€ 200000\n\n€ 200000000000\n\n\n€ 255000\n€ 2555000\n€ 255000";
if (preg_match_all('~€\s*\K\d+~u',$s, $matches)) {
    print_r(array_filter($matches[0], function ($m) { return $m % 5000 === 0; }));
}

模式 €\s*\K\d+ 匹配 ,然后是 0+ 个空白字符(使用 \s*),然后使用 \K 匹配重置运算符丢弃匹配字符,并且然后 \d+ 匹配 1 个或多个数字。

sample PHP demo 的输出:

Array
(
    [0] => 5000
    [2] => 10000
    [4] => 20000
    [5] => 5000
    [7] => 100000
    [9] => 200000
    [10] => 200000000000
    [11] => 255000
    [12] => 2555000
    [13] => 255000
)