Home > php教程 > PHP源码 > PHP中文字符串截取函数 - 开源中国社区

PHP中文字符串截取函数 - 开源中国社区

PHP中文网
Release: 2016-05-20 12:56:30
Original
1529 people have browsed it

跳至

	/**
	 * 中文字符串截取
	 * @param $str
	 * @param int $start @起始位置
	 * @param $length @截取长度
	 * @param string $ending @结尾符
	 * @return string
	 */
	private static function stringSubstr($str, $start=0, $length, $ending=''){
		//$str =  html_entity_decode($str); //实体字符转为html
		$str = trim(strip_tags($str)); //去除html字符
		$str = preg_replace("/\s| | /", "", $str);
		$mb_str = mb_substr($str, $start, $length, 'utf-8');
		if($length < method::abslength($str)){
			$output = $mb_str.$ending;
		}else{
			$output = $mb_str;
		}
		return $output;
	}

	/**
	 * 可以统计中文字符串长度的函数
	 * @param $str @要计算长度的字符串
	 * @return int @计算长度类型,0(默认)表示一个中文算一个字符,1表示一个中文算两个字符
	 */
	private static function abslength($str){
		if(empty($str)){
			return 0;
		}

		if(function_exists(&#39;mb_strlen&#39;)){
			return mb_strlen($str,&#39;utf-8&#39;);
		} else {
			preg_match_all("/./u", $str, $ar);
			return count($ar[0]);
		}
	}
Copy after login

                   

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template