search
HomeBackend DevelopmentPHP TutorialPHP string encoding conversion program_PHP tutorial

PHP string encoding conversion program_PHP tutorial

Jul 13, 2016 am 10:56 AM
gbkphpexistcharacterstringusBundleprogramcodingConvert

We often have to convert UFT-8 characters into gbk or gb2312 encoding, but we often encounter some problems in the conversion process. Let me introduce the use of PHP's own string conversion function to realize characters. Transcoding.

A bug in the iconv function. iconv will make an error when converting the character "-" to gb2312
The solution is very simple, just add “//IGNORE” after the encoding that needs to be converted, which is the second parameter of the iconv function.
As follows:
The following is the quoted content:

echo '
';
The code is as follows
 代码如下 复制代码
iconv(“UTF-8″,”GB2312//IGNORE”,$data)
Copy code

iconv("UTF-8″,"GB2312 //IGNORE”,$data)

 代码如下 复制代码

echo $str= '你好,这里是卖咖啡!';
echo '
';

echo iconv('GB2312', 'UTF-8', $str);      //将字符串的编码从GB2312转到UTF-8
echo '
';

echo iconv_substr($str, 1, 1, 'UTF-8');   //按字符个数截取而非字节
print_r(iconv_get_encoding());            //得到当前页面编码信息

echo iconv_strlen($str, 'UTF-8');         //得到设定编码的字符串长度

//也有这样用的

   $content = iconv("UTF-8","gbk//TRANSLIT",$content);
?>

ignore means to ignore errors during conversion. Without the ignore parameter, all strings following this character cannot be saved.

The iconv() function is built-in in php5.

Lie Zi

The code is as follows Copy code
 代码如下 复制代码

function phpcharset($data, $to) {
 if(is_array($data)) {
  foreach($data as $key => $val) {
   $data[$key] = phpcharset($val, $to);
  }
 } else {
  $encode_array = array('ASCII', 'UTF-8', 'GBK', 'GB2312', 'BIG5');
  $encoded = mb_detect_encoding($data, $encode_array);
  $to = strtoupper($to);
  if($encoded != $to) {
   $data = mb_convert_encoding($data, $to, $encoded);
  }
 }
 return $data;
}
?>

 代码如下 复制代码


function asciitog($brand)
{
 $cha=mb_detect_encoding($brand);
 if($cha=='utf-8')
 {
   $brand2 = iconv($cha,"gb2312",$brand);
 }
 $cha2=mb_detect_encoding($brand2);
 if($cha2!='ascii'){
  $brand=$brand2;
 }
 
 return $brand;
}

echo $str= 'Hello, we sell coffee here!';
echo iconv('GB2312', 'UTF-8', $str); //Convert the string encoding from GB2312 to UTF-8 echo '
'; echo iconv_substr($str, 1, 1, 'UTF-8'); //Truncate by the number of characters instead of bytes print_r(iconv_get_encoding()); //Get the encoding information of the current page echo iconv_strlen($str, 'UTF-8'); //Get the string length of the set encoding //This is also used $content = iconv("UTF-8","gbk//TRANSLIT",$content); ?> However, when using the iconv function, you may encounter notices such as: iconv() [function.iconv]: detected an illegal character in input string... Error, The reason is because of the encoding range problem. gb2312 is smaller than gbk and uft8, so everyone should pay attention when converting. However, our php also provides a function mb_detect_encoding which can better solve this problem. Now write it into a more professional function
The code is as follows Copy code
function phpcharset($data, $to) { if(is_array($data)) { foreach($data as $key => $val) { $data[$key] = phpcharset($val, $to); } } else { $encode_array = array('ASCII', 'UTF-8', 'GBK', 'GB2312', 'BIG5'); $encoded = mb_detect_encoding($data, $encode_array); $to = strtoupper($to); if($encoded != $to) { $data = mb_convert_encoding($data, $to, $encoded); } } return $data; } ?> Sometimes we don’t know the encoding of a character, and we need to detect the encoding first and then convert it.
The code is as follows Copy code
function asciitog($brand) { $cha=mb_detect_encoding($brand); if($cha=='utf-8') { $brand2 = iconv($cha,"gb2312",$brand); } $cha2=mb_detect_encoding($brand2); if($cha2!='ascii'){ $brand=$brand2; } return $brand; }

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632143.htmlTechArticleWe often encounter the problem of converting UFT-8 characters into gbk or gb2312 encoding, but during use We often encounter some problems. Let me introduce how to use the string conversion function that comes with PHP...
Statement
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
PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version