PHP preg_match 模式是主题的子串

PHP preg_match pattern is substring of subject

我想测试输入是否为 1234567(7 位数字)类型。 我用

preg_match($pattern,$subject);

其中

$pattern = '/^[0-9]{7}$/';

但是对于主题是

的情况,我得到 1
L-8987765

我不想要。我该如何克服这个问题?

   function isDocid($documento_id)
      {
       $subject = pg_escape_literal($documento_id);
       $pattern1 = '/^[0-9]{7}$/';

            if (preg_match($pattern1, $subject) === 1) 
            {
            return 1;
            }
            else
            {
            return 0;
            }}

$test_carta = isDocid('L-8987765');
echo('<p> ja existe docid   '. $test_carta  .'</p>');

我期待: 存在 docid 0

来自 the documentation(斜体是我的):

pg_escape_literal() escapes a literal for querying the PostgreSQL database. It returns an escaped literal in the PostgreSQL format. pg_escape_literal() adds quotes before and after data.

换句话说,由于引号的存在,您永远不会从正则表达式检查中获得肯定的结果。在准备好将数据插入数据库查询之前,不要使用数据库转义。或者,更好的是,不要将 PHP 变量插入数据库查询——而是使用 prepared statements

function isDocid($documento_id)
{
   return (preg_match('/^[0-9]{7}$/', $documento_id) === 1) ? 1 : 0;
}

$test_carta = isDocid('L-8987765');
echo('<p> ja existe docid   '. $test_carta  .'</p>');