php提取字符串中的手机号码或固话

一、php提取字符串中的手机号码或固话

/*通用方法*/

function findNum($str='')

{        

$str=trim($str);       

 if(empty($str))

{

return '';

}        

$reg= "/[^0-9+]*(?P(\+86[0-9]{11})|([0-9]{11})|([0-9]{3,4}-[0-9]{7,10}))[^0-9+]*/";

preg_match_all($reg,$str,$result); if(is_array($result)&&!empty($result)&&!empty($result[1])&&!empty($result[1][0]))

{

return $result[1][0];

}

return '';

}

二、另外附上PHP提取字符串中的数字的方法我觉得两个方法应该都是常用所以放在一起推荐

使用in_array方法:

function findNum($str=''){

$str=trim($str);

if(empty($str)){return '';}

$temp=array('1','2','3','4','5','6','7','8','9','0');

$result='';

for($i=0;$i

if(in_array($str[$i],$temp)){

$result.=$str[$i];

}

}

return $result;

}

使用is_numeric函数:

function findNum($str=''){

$str=trim($str);

if(empty($str)){return '';}

$result='';

for($i=0;$i

if(is_numeric($str[$i])){

$result.=$str[$i];

}

}

return $result;

}

三、也是跟提取字符串有关系的方法  就是把字符串中的号码进行替换可以是完全的替换可拨打的链接也可以替换为*号

function hidtel($phone)

{

$IsWhat = preg_match('/(0[0-9]{2,3}[\-]?[2-9][0-9]{6,7}[\-]?[0-9]?)/i',$phone); //固定电话

if($IsWhat == 1)

{

return preg_replace('/(0[0-9]{2,3}[\-]?[2-9])[0-9]{3,4}([0-9]{3}[\-]?[0-9]?)/i','$1****$2',$phone);

}else

{

return  preg_replace('/(1[358]{1}[0-9])[0-9]{4}([0-9]{4})/i','$1****$2',$phone);

}

}

提示:想换成可点击的拨打电话链接可以这样,对比下着两端代码 其实区别就在于$0-$1-$2 而已,$0是获取匹配到的完整号码,$1是获取前三位,$2是获取后4位

function hidtel($phone)

{    

$IsWhat = preg_match('/(0[0-9]{2,3}[\-]?[2-9][0-9]{6,7}[\-]?[0-9]?)/i',$phone); //固定电话  

  if($IsWhat == 1)

{        

return preg_replace('/(0[0-9]{2,3}[\-]?[2-9])[0-9]{3,4}([0-9]{3}[\-]?[0-9]?)/i','$0',$phone);   

 }else

{        

return  preg_replace('/(1[358]{1}[0-9])[0-9]{4}([0-9]{4})/i','$0',$phone);    

}

}

你可能感兴趣的:(php提取字符串中的手机号码或固话)