dswg47377 2019-05-14 15:33
浏览 95
已采纳

PHP preg_match模式是主题的子串

I want to test if an input is of the type 1234567 (7 digits). I use

preg_match($pattern,$subject);

where

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

However I get 1 for the case where the subject is

L-8987765

Which I do not want. How can I overcome this?

   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>');

I am expecting: ja existe docid 0

  • 写回答

1条回答 默认 最新

  • doulupian8725 2019-05-14 20:54
    关注

    From the documentation (italics are mine):

    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.

    In other words, you were never going to get a positive result from your regular expression check because of the quotes in the way. Don't use database escapes until you are ready to insert data into a database query. Or, better yet, don't insert a PHP variable into a database query – use prepared statements instead.

    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>');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)