2

我的 PHP 函数遇到了一点问题。

我创建了一个PHP函数,160个字符后扣除1个SMS积分,320个字符后扣除2个SMS积分等等,但最近我观察到151个字符或小于160个字符的文本会扣除2个SMS积分。我不知道是否有任何隐藏字符或者我没有转义某些字符串。

下面是PHP代码:

//=== function to deduct credit per sms

function deduct_sms_credit( $user_id, $msg ) {
    $per_sms = 160;

    //calculate the no. Of sms pages with ceil() function
    $no_pg_sms = ceil( strlen( $msg ) / $per_sms );
    $sms_amount = $no_pg_sms;
    $query = "SELECT * FROM sms_history WHERE user_id=".$user_id."";
    $result = mysql_query( $query );
    while( $rs = mysql_fetch_array( $result ) ) {
        $remaining = $rs['remaining'] - $sms_amount;
        $spent = $rs['spent'] + $sms_amount;
    }
    $qupdate = "UPDATE sms_history SET `remaining` = ".$remaining.", `spent` = ".$spent." WHERE user_id = ".$user_id."";
    mysql_query( $qupdate );    
}

我尝试发送包含以下内容的短信:

尊敬的客户,对于上周登录时遇到的问题,我们深表歉意,请按照以下链接重置您的密码http://bit.ly/i5ud1zhm,www.boltsns238.com

它向我收取了 2 个学分而不是 1 个学分。我需要任何 PHP 函数的帮助来修剪、转义或解决问题。

4

2 回答 2

0

我修改了你的功能

function deduct_sms_credit( $user_id, $msg ) {
     $per_sms = 160;
     $no_pg_sms = 0;

     $len = mb_strlen($msg);

     if($len<=160)
     {
        $no_pg_sms = 0;
     }
     else if ($len % $per_sms == 0) {
         $no_pg_sms = $len / $per_sms;
      } else {
          $str_sms = chunk_split($msg,160,"|*|");
          $arr_sms = explode("|*|", $str_sms);
          foreach($arr_sms as $key=>$value)
          {
             if(mb_strlen($value) !== 0)
                 $no_pg_sms++;
          }
    }

    $sms_amount = $no_pg_sms;
    $query = "SELECT * FROM sms_history WHERE user_id=".$user_id."";
    $result = mysql_query( $query );
    while( $rs = mysql_fetch_array( $result ) ) {
      $remaining = $rs['remaining'] - $sms_amount;
      $spent = $rs['spent'] + $sms_amount;
  }
  $qupdate = "UPDATE sms_history SET `remaining` = ".$remaining.", `spent` = ".$spent."   WHERE user_id = ".$user_id."";
  mysql_query( $qupdate );    
  }

请试试这个,让我知道

于 2013-08-14T09:33:55.430 回答
-1

也许你应该试试函数 mb_strlen

http://ca3.php.net/manual/en/function.mb-strlen.php

可能的问题是您传递的 $msg 是一个 unicode 字符串或其他一些多字节编码(例如 utf-8)。在这种情况下,strlen 将为每 1 个字符或更多字符返回 2,从而使您的 strlen 膨胀。

//=== function to deduct credit per sms

function deduct_sms_credit( $user_id, $msg ) {
    $per_sms = 160;

    //calculate the no. Of sms pages with ceil() function
    $no_pg_sms = ceil( mb_strlen( $msg ) / $per_sms );
    $sms_amount = $no_pg_sms;
    $query = "SELECT * FROM sms_history WHERE user_id=".$user_id."";
    $result = mysql_query( $query );
    while( $rs = mysql_fetch_array( $result ) ) {
        $remaining = $rs['remaining'] - $sms_amount;
        $spent = $rs['spent'] + $sms_amount;
    }
    $qupdate = "UPDATE sms_history SET `remaining` = ".$remaining.", `spent` = ".$spent." WHERE user_id = ".$user_id."";
    mysql_query( $qupdate );    
}
于 2013-08-15T16:22:37.277 回答