提供一些项目中常用的字符串操作功能包括:截取字符串长度、输出转换、随机字符串、全角半角转换、字符集转换、邮箱格式验证、数字转文件大小.
截取字符串长度代码段:
<span style="font-family:SimSun;font-size:12px;">/** * 截取长度 * @param unknown $str * @param number $start * @param unknown $length * @param string $charset * @param string $suffix * @return mixed|string */ public static function GetCsubStr($str,$start=0,$length,$charset="utf-8",$suffix=true){ $charset=empty($charset)?'utf-8':$charset; $search=array('((\\\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)(\[[a-zA-Z0-9\-\.\[\]_\"\'\$\x7f-\xff]+\])*)','/<(\/?)(script|i?frame|style|html|body|title|link|meta|\?|\%)([^>]*?)>/isU', // 去掉 javascript '/(<[^>]*)on[a-zA-Z] \s*=([^>]*>)/isU','/<[\/\!]*?[^<>]*?>/si', // 去掉 HTML 标记 '/([\r\n])[\s ]+/i', // 去掉空白字符 '/&(quot|#34);/i', // 替换 HTML 实体 '/&(amp|#38);/i','/&(lt|#60);/i','/&(gt|#62);/i','/&(nbsp|#160);/i','/&(iexcl|#161);/i','/&(cent|#162);/i','/&(pound|#163);/i','/&(copy|#169);/i','/&#(\d+);/e','/<\?/si','/\?>/si'); $replace=array('([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)','<\\1\\2\\3>','\\1\\2',"","\r\n","","","","","","","","","","",'<?','?>'); $str=preg_replace($search,$replace,$str); if(function_exists("mb_substr")){ if(mb_strlen($str,$charset)<=$length){return $str;} $slice=mb_substr($str,$start,$length,$charset); }else{ $re['utf-8']="/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/"; $re['gb2312']="/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/"; $re['gbk']="/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/"; $re['big5']="/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/"; preg_match_all($re[$charset],$str,$match); if(!empty($match[0])&&count($match[0])<=$length){return $str;} $slice=join("",array_slice($match[0],$start,$length)); } if($suffix){return $slice."…";} return $slice; }</span>
preg_replace : 详细请查阅:PHP使用正则表达式查找替换字符串
代码段持续更新中...如果没有你需要的,可以留下你的评论,告诉你的需求.
谢谢关注websites博客.
原文地址:http://blog.csdn.net/websites/article/details/45246001