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 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题