Perl将单引号替换为双引号字符串

时间:2014-04-02 03:13:39

标签: regex perl replace double-quotes

我的脚本想要用双引号替换或删除单引号 str_replace(rtrim(c_manager),~s / \'/ \'\'/ g)这行无法解决..

示例:k'amal

结果:k“amal or kamal

$sql = 'select rtrim(f_admin_disabled),'."\n".

                '       convert(varchar,t_password,101),'."\n".

                '       rtrim(c_email),'."\n".

                '       str_replace(rtrim(c_manager),~s/\'/\'\'/g),'."\n".

                '       rtrim(c_mgr_email)'."\n".

                '  from tuserprofile'."\n".

                ' where ic_user1 = '."'$user_id'"."\n";


         $sth = $dbh->prepare("$sql")
            or err("Database error in $sql", "Error preparing SQL statement:\r\n\n" . $dbh->errstr, 3);
         $sth->execute or err("Database error in $sql", "Error executing SQL statement:\r\n\n" . $dbh->errstr, 3);
         $sth->bind_columns(\$prev_status, \$prev_date, \$prev_email, \$prev_mngr_name, \$prev_mngr_email);
         $sth->fetch();
         $sth->finish();

         if($user_email ne $prev_email){

            $sql = 'declare @result int'."\n".
                   'exec @result = ap_recert_update '."'$user_id', '$prev_date', ".
                                                      "'$prev_status', '$user_email', ".
                                                      "'$prev_mngr_name', '$prev_mngr_email'  "."\n".
                   'SELECT @result'."\n";

            $sth = $dbh->prepare("$sql")
               or err("Database error in $sql", "Error preparing SQL statement:\r\n\n" . $dbh->errstr, 3);
            $sth->execute or err("Database error in $sql", "Error executing SQL statement:\r\n\n" . $dbh->errstr, 3);
            $sth->bind_columns( \$result);
            $sth->fetch();

            if($result < 0){
               err("", $user_id."\t".$result, 0);
               $problem = $problem.$user_id."\t".$result."\n";
            }
            $sth->finish();
         }
      }
   }

1 个答案:

答案 0 :(得分:4)

不要将变量直接包含在sql语句中。而是使用placeholders and bind variables

清理你的第一个sql语句将如下所示:

my $sql = q{select rtrim(f_admin_disabled),
    convert(varchar,t_password,101),
    rtrim(c_email),
    str_replace(rtrim(c_manager),~s/'/''/g),
    rtrim(c_mgr_email)
    from tuserprofile
    where ic_user1 =?};

$sth = $dbh->prepare($sql)
    or err("Database error in $sql", "Error preparing SQL statement:\r\n\n" . $dbh->errstr, 3);
$sth->execute($user_id) or err("Database error in $sql", "Error executing SQL statement:\r\n\n" . $dbh->errstr, 3);
$sth->bind_columns(\($prev_status, $prev_date, $prev_email, $prev_mngr_name, $prev_mngr_email));
$sth->fetch();
$sth->finish();

也可以使用heredoc进行$sql

的作业
my $sql = <<'END_SQL';
select rtrim(f_admin_disabled),
  convert(varchar,t_password,101),
  rtrim(c_email),
  str_replace(rtrim(c_manager),~s/'/''/g),
  rtrim(c_mgr_email)
  from tuserprofile
  where ic_user1 =?
END_SQL