---
title: "php 字符转换"
author: "yunmoxue"
date: "2011-11-20T09:05:49Z"
tags: []
categories: ["编程语言"]
slug: "php"
draft: false
lastmod: "2011-11-20T09:09:33Z"
id: 1267787
url: "https://ymx.iteye.com/blog/1267787"
---

插入数据

将单引号(') 前加上\\ ,避免数据库插入错误. 

相关函数 : addcslashes($str,'\\'');

读取数据

将 &amp;,这三个字符转换成html实体(如不改变,在xml中将报错)

相关函数: htmlentities($str,ENT\_NOQUOTES);  //ENT\_NOQUOTES的意思是不转换 双引号(&quot;) 和 单引号(')

乱码

大部分乱码都是因为编码不一致造成的,可使用相关函数重新进行编码

相关函数: icovn(&quot;utf-8&quot;,&quot;ascii//TRANSLIT//IGNORE&quot;,$str);  // TRANSLIT 和 IGNORE 是 参数,分别是遇到特殊字符时停止编码,返回已编码的字符串 和 忽略不能编码的字符.

```
echo '/************addcslashes************/';
$str = 'abcdfegadsf\'asdfasdfa';
echo addcslashes($str,'\'');


echo '/************htmlentities*************/';
$str = 'abcdfe &amp; s  ha \'asdfasdfa';
echo htmlentities($str,ENT_NOQUOTES);

echo '/************iconv*************/';
$str = ' ‘ ’	€™â“„”¨¦œ©Ã¡ïï¿ ½ ¾ Ë ª ¢ ¢ ® @ @Weiß, Goldmann, Göbel, Weiss, Göthe, Goethe und Götz € aa';
//change encoding from utf-8 to ascii
echo  iconv('utf-8','ascii//TRANSLIT//IGNORE',$str);
```