Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

PHP – แปลง Character Encoding สตริงด้วย iconv()

ฟังก์ชัน iconv() ใช้แปลงสตริงจาก character encoding หนึ่งไปยังอีก encoding หนึ่ง ใช้ทำ character set conversion บนสตริง "string" จาก from_encoding ไป to_encoding

รูปแบบการใช้งาน (Syntax)

string iconv(string $from_encoding, string $to_encoding, string $string)

พารามิเตอร์

  • $from_encoding – input charset
  • $to_encoding – output charset สามารถเพิ่ม suffix //TRANSLIT (พยายาม transliterate ตัวอักษรที่ไม่มีใน target encoding) หรือ //IGNORE (ตัดทิ้งตัวอักษรที่แปลงไม่ได้)
  • $string – สตริงที่ต้องการแปลง

ค่าที่คืนกลับ

คืนสตริงที่แปลงแล้วเมื่อสำเร็จ คืน false เมื่อล้มเหลว

ตัวอย่าง 1: สัญลักษณ์ดอลลาร์

<pre>
<?php
$text = "the Dollar symbol '$'";
echo 'Original:', $text, PHP_EOL;
echo 'TRANSLIT: ', iconv("UTF-8", "ISO-8859-1//TRANSLIT", $text), PHP_EOL;
echo 'IGNORE: ', iconv("UTF-8", "ISO-8859-1//IGNORE", $text), PHP_EOL;
?>
</pre>

ผลลัพธ์

Original: the Dollar symbol '$'
TRANSLIT: the Dollar symbol '$'
IGNORE: the Dollar symbol '$'

ตัวอย่าง 2: สัญลักษณ์รูปีอินเดีย

<pre>
<?php
$string = "Indian Rupees '?'";
echo 'Original: ', $string, PHP_EOL;
echo 'TRANSLIT : ', iconv("UTF-8", "ISO-8859-1//TRANSLIT", $string), PHP_EOL;
echo 'IGNORE: ', iconv("UTF-8", "ISO-8859-1//IGNORE", $string), PHP_EOL;
?>
</pre>

ผลลัพธ์

Original: Indian Rupees '?'
TRANSLIT: Indian Rupees '?'
IGNORE: Indian Rupees '?'