---
title: "PHP自定义函数实现防止中文出现乱码"
author: "cakin24"
date: "2016-12-31T07:28:26Z"
tags: []
categories: ["编程语言"]
slug: "php"
draft: false
lastmod: "2016-12-31T07:28:26Z"
id: 2348292
url: "https://cakin24.iteye.com/blog/2348292"
---

**一 代码**

function.php

01. `<?php`
02. `function chinesesubstr($str,$start,$len){`
03. `$strlen=$start+$len;`
04. `for($i=0;$i<$strlen;$i++){`
05. `if(ord(substr($str,$i,1))>0xa0){`
06. `$tmpstr.=substr($str,$i,2);`
07. `$i++;`
08. `}else`
09. `$tmpstr.=substr($str,$i,1);`
10. `}`
11. `return $tmpstr;`
12. `}`
13. `?>`

index.php

01. `<linkrel="stylesheet"type="text/css"href="style.css">`
02. `<tablewidth="160"border="0"align="center"cellpadding="0"cellspacing="0">`
03. `<tr>`
04. `<tdwidth="165"height="32"><imgsrc="images/tell_top.gif"width="165"`
05. `height="32"border="0"></td>`
06. `</tr>`
07. `<tr>`
08. `<tdheight="52"background="images/tell_center.gif">`
09. `<?php`
10. `include_once("function.php");`
11. `$news="中小学因雾霾放假！";`
12. `$i=1;`
13. `do{`
14. `?>`
15. `<tablewidth="148"height="25"border="0"align="center"cellpadding="0"`
16. `cellspacing="0">`
17. `<tr>`
18. `<tdwidth="17"height="20"><imgsrc="images/mark_0.gif"width="10"`
19. `height="10"></td>`
20. `<tdwidth="333">`
21. `<?php`
22. `echo chinesesubstr($news,0,16);`
23. `if(strlen($news)>16){`
24. `echo " ...";`
25. `}`
26. `?>`
27. `</td>`
28. `</tr>`
29. `<tr>`
30. `<tdheight="5"></td>`
31. `<tdheight="5"background="images/back_point_write.gif"></td>`
32. `</tr>`
33. `</table>`
34. `<?php`
35. `$i++;`
36. `}while($i<=5);`
37. `?>`
38. `</td>`
39. `</tr>`
40. `<tr>`
41. `<tdwidth="165"height="12"><imgsrc="images/tell_bottom.gif"width="165"`
42. `height="12"></td>`
43. `</tr>`
44. `</table>`

**二 运行效果**

![](http://dl2.iteye.com/upload/attachment/0122/3315/1b3ad0ad-c2e1-3237-8bbc-3269fc1fed2d.png)  
 

**三 代码说明**

1、为了保持整个页面合理布局，经常需要对一些较长的字符进行部分输出，但由于汉字占有两个字符，如果截取位置不当就可能导致截取的字符串尾出现乱码。

2、本代码实现功能：创建一个自定义函数，用于实现屏蔽中文乱码的输出，将该函数封装在一个function.php中，然后应用include\_once语句引用这个文件，再通过echo语句输出新闻主题信息，截取前16个 字符，并应用自定义函数屏蔽中文乱码。