我的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个学分而不是一个学分。我需要任何PHP函数的帮助来修剪,转义或解决问题。
答案 0 :(得分: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 );
}
请尝试这个并告诉我
答案 1 :(得分:-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 );
}