PHP preg_match用户编号列表输入

时间:2014-09-11 18:02:03

标签: php mysql wordpress plugins preg-match

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

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

回答奖励:如果可能,请确保然后输出,这样就不会破坏SQL。此代码只接受或拒绝输入而不“修复”它。

Good Numbers =“213”或“213,252” 坏数字=空白,“二七十三”,“红色是一种颜色。”

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";

2 个答案:

答案 0 :(得分:2)

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

/^[0-9,]+$/

奖金(检查不中断SQL):

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

相同但允许空格:

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

您可以在此处尝试各种表达:http://regex101.com/r/rD9oC7/1

答案 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/