---
title: "PHP截取固定长度字符串函数"
author: "javaeyeren"
date: "2009-02-02T16:19:00Z"
tags: []
slug: "php"
draft: false
lastmod: "2009-02-02T16:19:00Z"
id: 601317
url: "https://javaeyeren.iteye.com/blog/601317"
---

&lt;?php

functiontoFixLen($str,$len){//固定长度字符串的截取

if($len&gt;=strlen($str)||!$len)return$str;

$len-=3;

$tempstr1=substr($str,0,$len);//截取字符串

$tempstr2=preg\_replace('/(\[\\x81-\\xff]+)$/ms','',$tempstr1,1);//去掉结尾的连续汉字字符

if(!is\_int((strlen($tempstr1)-strlen($tempstr2))/2)){//去掉的字符为奇数?

$tempstr1=substr($str,0,$len-1);

}

return$tempstr1."…";

}

?&gt;