<?php
/**
* 该文件,旨在为了去除php string里的bom
* bom存在的可能性有:1个或2个,
* 1个的位置可能是: 首部,尾部,中间
* 2个可能的位置是首部+尾部
* @return $res['val'] 即为最终的结果
* @param $handle_ok 0代表仍有bom 1代表bom清除完毕
*/
$contents = '13512340680 '; // This character contains 'bom' 226 128 172
//$contents = '13812340919'; //
//$contents = '15812349681 '; //
//$contents = '13712346524'; //
//$contents = 's13512340680'; //
// Step 1: trim
$contents = trim($contents);
function RemoveBom($contents,$handle_ok=0){
// Step 2: extract the length of this str,judge it if contains 有bom(process)
$length = strlen($contents);
$have_bom = 0;
// The position of bom
$bom_position = 0;
for($i=0;$i<$length;$i++){
$temp_single_element = substr($contents,$i,1);
$is_num = ord($temp_single_element);
if( $is_num >= 48 && $is_num <= 57 ){
// no code in this line
}else{
$have_bom = 1;
$bom_position = $i;
break;
}
}
// Step 3: Judge if have bom(result), if have ,then remove it :the position of bom: a. header b. footer c. middle
if($have_bom==1){
// Judge header
if($bom_position==0){
//echo 'header';die;
$res['handle_ok'] = 0 ;
$res['val'] = substr($contents,3); // If no the third param, its default value is until to the tail of this string
return $res ;
// Judge footer
}else if( $bom_position == ($length-3) ){
//echo 'footer';die;
$res['handle_ok'] = 0 ;
$res['val'] = substr($contents,0,$length-3 );
return $res ;
// Judge middle
}else {
//echo 'middle';die;
$starter = substr($contents,0,$bom_position );
$ender = substr($contents,$bom_position+3 );
$res['handle_ok'] = 0 ;
$res['val'] = $starter . $ender ;
return $res ;
}
}else{
// No bom
$res['handle_ok'] = 1;
$res['val'] = $contents;
return $res ;
}
}
$res = RemoveBom($contents); // Remove the first one
$res = RemoveBom($res['val']); // Remove the second one
$res = RemoveBom($res['val']); // make $handle_ok become one
if($res['handle_ok']==1){
var_dump($res);
die;
}else{
echo 'Still have bom';
die;
}
// Judge if it is phone number with Regular Expression
网友评论