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

PHP – ตัดส่วนของสตริงด้วย iconv_substr()

ฟังก์ชัน iconv_substr() ใช้ตัดส่วนของสตริงที่ระบุโดย offset และ length parameters ตัวอย่าง: สตริง "helloWorld" ต้องการตัดเฉพาะ "llowo" ให้เลือก offset 2 ถึง 5

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

string iconv_substr(string $string, int $offset, int $length = null, string $encoding = null)

พารามิเตอร์

  • $string – สตริงต้นทาง
  • $offset – ตำแหน่งเริ่มต้น (0 = อักขระแรก) หากเป็นค่าลบ จะนับจากท้ายสตริง
  • $length – จำนวนอักขระสูงสุดที่ต้องการ หากเป็นบวก จะคืนสูงสุด length อักขระจาก offset
  • $encoding – character encoding หากละเว้นหรือ null จะใช้ iconv.internal_encoding

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

คืนส่วนของสตริงตาม offset และ length คืน false หากสตริงสั้นกว่า offset คืน empty string หากความยาวเท่ากับ offset

ตัวอย่าง 1: ไม่มี space

<?php
$string = iconv_substr("HelloWorld!", 2, 7, "UTF-8");
var_dump($string);
?>

ผลลัพธ์

string(7) "lloWorl"

ตัวอย่าง 2: มี space

<?php
$string = iconv_substr("Hello World!", 2, 7, "UTF-8");
var_dump($string);
?>

ผลลัพธ์

string(7) "llo Wor"