PHP substr_count()ฟังก์ชั่น
ตัวอย่าง
นับจำนวนครั้งที่ "โลก" เกิดขึ้นในสตริง:
<?php
echo substr_count("Hello world. The world is nice","world");
?>
ฟังก์ชัน substr_count() นับจำนวนครั้งที่สตริงย่อยเกิดขึ้นในสตริง
หมายเหตุ:สตริงย่อยคำนึงถึงขนาดตัวพิมพ์
หมายเหตุ:ฟังก์ชันนี้ไม่นับสตริงย่อยที่ทับซ้อนกัน (ดูตัวอย่างที่ 2)
หมายเหตุ:ฟังก์ชันนี้จะสร้างคำเตือนหากพารามิเตอร์ start บวกกับพารามิเตอร์ length มากกว่าความยาวของสตริง (ดูตัวอย่างที่ 3)
ไวยากรณ์
substr_count(string,substring,start,length)
ค่าพารามิเตอร์
Parameter | Description |
---|---|
string | Required. Specifies the string to check |
substring | Required. Specifies the string to search for |
start | Optional. Specifies where in string to start searching. If negative, it starts counting from the end of the string |
length | Optional. Specifies the length of the search |
รายละเอียดทางเทคนิค
คืนมูลค่า: | ส่งกลับจำนวนครั้งที่สตริงย่อยเกิดขึ้นในสตริง |
---|---|
รุ่น PHP: | 4+ |
บันทึกการเปลี่ยนแปลง: | PHP 7.1 - พารามิเตอร์ ความยาวสามารถเป็น 0 หรือตัวเลขติดลบ PHP 7.1 - พารามิเตอร์ เริ่มต้นสามารถเป็นจำนวนลบได้ PHP 5.1 - เพิ่มพารามิเตอร์เริ่มต้นและความยาว แล้ว |
ตัวอย่างเพิ่มเติม
ตัวอย่าง
ใช้พารามิเตอร์ทั้งหมด:
<?php
$str = "This is nice";
echo strlen($str)."<br>"; // Using strlen() to return the string length
echo substr_count($str,"is")."<br>"; // The number of times "is" occurs in the string
echo substr_count($str,"is",2)."<br>"; // The string is now reduced to "is is nice"
echo substr_count($str,"is",3)."<br>"; // The string is now reduced to "s is nice"
echo substr_count($str,"is",3,3)."<br>"; // The string is now reduced to "s i"
?>
ตัวอย่าง
สตริงย่อยที่ทับซ้อนกัน:
<?php
$str = "abcabcab";
echo substr_count($str,"abcab"); // This function does not count overlapped substrings
?>
ตัวอย่าง
หากพารามิเตอร์เริ่มต้นและความยาวเกินความยาวของสตริง ฟังก์ชันนี้จะแสดงคำเตือน:
<?php
echo $str = "This is nice";
substr_count($str,"is",3,9);
?>
สิ่งนี้จะส่งคำเตือนเนื่องจากค่าความยาวเกินความยาวของสตริง (3+9 มากกว่า 12)
❮ การอ้างอิงสตริง PHP