Home > php教程 > PHP源码 > 非常实用的支持中英文字符串截取函数

非常实用的支持中英文字符串截取函数

PHP中文网
Release: 2016-05-25 17:04:19
Original
1239 people have browsed it

php代码

<?php
/**
 * @param string $string 需要截取的字符串
 * @param string $sublen 需要截取的长度(英文和中文都计算一个)
 * @param string $tags 需要保留的标签
 * @param string $endTag 最后截取位置标签(为保证不出现排版错乱,必须与$tags中第一个标签成对)
 * @return string
 */	
function _formatString($string,$sublen=100,$tags=&#39;&#39;,$endTag=&#39;&#39;){
	$string=stripslashes($string);
	$string=strip_tags($string,$tags);
	$string=str_ireplace("\t","",$string);
	$string=str_ireplace("\r\n","",$string);
	$string=str_ireplace("\r","",$string);
	$string=str_ireplace("\n","",$string);
	$string=str_ireplace(" ","",$string);
	$length=strlen($string);
	$tag_len=strlen($endTag);
	$new_str=mb_substr($string,0,$sublen,&#39;utf-8&#39;);
	$new_len=strlen($new_str);
	$end_len=strripos($new_str,$endTag)+$tag_len;	//最后一次出现标签位置再加上自身标签长度
	if($new_len!=$end_len){
		if($end_len==$tag_len){
			for($i=$new_len; $i <=$length; $i++){
				$str=substr($string,0,$i);
				if(strpos($str,$endTag)){
					$new_str=$str;
					break;
				}
			}
		}else{
			$new_str=substr($new_str,0,$end_len);
		}
	}
	return $new_str;
}
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