สมมติว่ามีสตริงดังนี้
$sentence = "This is my first PHP program";
ต้องการผลลัพธ์ดังนี้
This is my first PHP ... gram
ย่อสตริงด้วย "..." สำหรับกรณีนี้ ใช้แนวคิด substring() และตั้งเงื่อนไขโดยตรวจสอบจำนวนคำ
ตัวอย่างโค้ด
<!DOCTYPE html> <html> <body> <?php $sentence = "This is my first PHP program"; if (strlen($sentence) >= 13) { echo substr($sentence, 0, 20) . " ... " . substr($sentence, -4); } else { echo $sentence; } ?> </body> </html>ผลลัพธ์
This is my first PHP ... gram