【问题标题】:PHP preg_match User Number List InputPHP preg_match 用户编号列表输入
【发布时间】:2014-11-05 19:13:48
【问题描述】:

我正在对 WordPress 插件进行小修改。用户将页面/帖子编号输入到他们想要从列表中排除的文本框中。

我需要过滤输入,然后检查它是否应该包含在 mySQL SELECT 中。有人可以帮忙解决这个问题吗?我似乎无法让它工作。我对 preg_match 表达式不是很熟悉。我想确保输入中只有数字和逗号。测试不同的 preg_match 总是在我身上返回 0。

Answer Bonus:如果可能,请确保它被输出,这样它就不会破坏 SQL。此代码只是接受或拒绝进入,而不“修复”它。

好数字 = "213" 或 "213, 252" Bad Numbers = 空白、“二七十三”、“红色是一种颜色。”

PHP

if ((!empty($excludedPagesPosts)) && (preg_match('/^[0-9\,]$/', $excludedPagesPosts))){
    $exclude = 'ID Not In ($excludedPagesPosts) And';
} else {
    $exclude = '';
}

mySQL

$sql = "    SELECT 
                ID, 
                post_title, 
                post_modified 
            FROM
                {$wpdb->posts} 
            WHERE
                $exclude
                post_status = 'publish' AND
                {$postTypeWhere} 
            ORDER BY post_modified DESC";

【问题讨论】:

    标签: php mysql wordpress plugins preg-match


    【解决方案1】:

    您的正则表达式只匹配一个字符。要匹配一个或多个字符,请添加+。也没有必要逃避,。所以正确的表达方式:

    /^[0-9,]+$/
    

    奖励(检查不中断 SQL):

    /^[0-9]+(,[0-9]+)*$/
    

    相同但允许空格:

    /^ *[0-9]+ *(, *[0-9]+ *)*$/
    

    您可以在这里尝试各种表达方式:http://regex101.com/r/rD9oC7/1

    【讨论】:

    • 感谢它的工作!很高兴知道它可以做这两件事。也感谢您的链接。我肯定会在未来使用它。
    【解决方案2】:

    这就足够了:

    if (preg_match('/\A[0-9]+(?:,[0-9]+)*\z/', $excludedPagesPosts))
    

    无需测试$excludedPagesPosts 是否为空,因为这种情况下模式会失败。

    模式详情:

    \A           # anchor for the start of the string
    [0-9]+       # one or more digits
    (?:          # open a non-capturing group
        ,        # literal comma (no need to escape it)
        [0-9]+   # one or more digits
    )*           # repeat the group zero or more times
    \z           # anchor for the end of the string
    

    注意:您可以在逗号后添加一个可选空格:/\A[0-9]+(?:, ?[0-9]+)*\z/

    【讨论】:

    • 感谢您不检查是否为空的提醒。这是有道理的,它会在空的 preg_match 上失败。
    猜你喜欢
    • 1970-01-01
    • 2017-04-17
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-25
    • 1970-01-01
    相关资源
    最近更新 更多