การตัดข้อความหรือเนื้อหาให้สั้นลง แล้วใส่ ... หลังข้อความ 106
หน้าแรก PHP MySQL เกร็ดความรู้ การตัดข้อความหรือเนื้อหาให้สั้นลง แล้วใส่ ... หลังข้อความ 106
สวัสดีครับ วันนี้ ' จารย์ ด๋อยมี Source Code ดีๆ มานำเสนอนั่นคือ การใช้ PHP ตัดข้อความหรือเนื้อหาให้สั้นลง ถ้าข้อความหรือเนื้อหานั้นมีความยาวตัวอักษรเกินกว่าที่กำหนด และเมื่อตัดแล้วจะทำการใส่เครื่องหมาย ... หลังข้อความที่ตัดเพื่อเป็นกับบอกว่าข้อความนี้ยังมีต่อครับ โดยให้คุณ Copy Function ต่อไปนี้ลงไปใน File ของคุณครับ
ส่วนการประกาศ Function
| Code |
| function utf8_to_tis620($string) { $str = $string; $res = ""; for ($i = 0; $i < strlen($str); $i++) { if (ord($str[$i]) == 224) { $unicode = ord($str[$i+2]) & 0x3F; $unicode |= (ord($str[$i+1]) & 0x3F) << 6; $unicode |= (ord($str[$i]) & 0x0F) << 12; $res .= chr($unicode-0x0E00+0xA0); $i += 2; } else { $res .= $str[$i]; } } return $res; } function substr_utf8( $str, $start_p , $len_p) { $str_post = ""; if(strlen(utf8_to_tis620($str)) > $len_p) { $str_post = "..."; } return preg_replace( '#^(?:[x00-x7F]|[xC0-xFF][x80-xBF]+){0,'.$start_p.'}'. '((?:[x00-x7F]|[xC0-xFF][x80-xBF]+){0,'.$len_p.'}).*#s', '$1' , $str ) . $str_post; }; |
ตัวอย่างการนำไปใช้งาน
| Code |
| <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>ทดสอบการตัดข้อความหรือเนื้อหา</title> </head> <body> <?php //- ส่วนของการประกาศ Function -------------------------------------------------------- function utf8_to_tis620($string) { $str = $string; $res = ""; for ($i = 0; $i < strlen($str); $i++) { if (ord($str[$i]) == 224) { $unicode = ord($str[$i+2]) & 0x3F; $unicode |= (ord($str[$i+1]) & 0x3F) << 6; $unicode |= (ord($str[$i]) & 0x0F) << 12; $res .= chr($unicode-0x0E00+0xA0); $i += 2; } else { $res .= $str[$i]; } } return $res; } function substr_utf8( $str, $start_p , $len_p) { $str_post = ""; if(strlen(utf8_to_tis620($str)) > $len_p) { $str_post = "..."; } return preg_replace( '#^(?:[x00-x7F]|[xC0-xFF][x80-xBF]+){0,'.$start_p.'}'. '((?:[x00-x7F]|[xC0-xFF][x80-xBF]+){0,'.$len_p.'}).*#s', '$1' , $str ) . $str_post; }; //-------------------------------------------------------------------------------------------- //- ตัวอย่างการใช้งาน ---------------------------------------------------------------------- $str = "ทดสอบการตัดข้อความหรือเนื้อหากรณีที่ข้อความหรือเนื้อหานั้นยาวกว่าที่ต้องการ"; echo substr_utf8( $str, 0 , 10); echo "<br/>"; echo substr_utf8( $str, 0 , 20); echo "<br/>"; echo substr_utf8( $str, 0 , 30); //-------------------------------------------------------------------------------------------- ?> </body> </html> |
ผลลัพธ์

ขึ้นไปด้านบน
