ใน PHP 8 ฟังก์ชัน str_contains ใช้กำหนดว่าสตริงมี substring ที่กำหนดอยู่ที่ไหนก็ได้ ฟังก์ชัน str_contains ตรวจสอบว่าสตริงแรกอยู่ในสตริงที่สองหรือไม่ และคืนค่าบูลลีน true/false ตามว่าพบสตริงหรือไม่ เป็นฟังก์ชันที่อธิบายตัวเองได้ (self-explanatory)
str_contains(string $haystack, string $needle): bool
ตัวอย่างที่ 1: PHP 8 str_contains function
<?php
if (str_contains('great reading tutorial', 'tutorial')) {
var_dump('Tutorial has been found');
} ?>
ผลลัพธ์
string(23) "Tutorial has been found"
ตัวอย่าง: str_contains function
<?php
if (str_contains('great reading tutorial', 'hello')){
var_dump('great reading');
} ?>
หมายเหตุ: โปรแกรมด้านบนคืนค่า false เนื่องจากสตริงแรกไม่มีสตริงที่สอง
ฟังก์ชัน strpos()
ใน PHP 7.x ฟังก์ชัน strpos() ใช้ตรวจสอบว่าสตริงที่กำหนดมีสตริงอื่นหรือไม่ ฟังก์ชันนี้คืนค่าตำแหน่งของสตริง needle หรือคืนค่า false หากไม่พบ needle
if (strpos('string with lots of words', 'words') !== false) { /* ... */ }
ตัวอย่าง: PHP 7.x strpos() function
<?php
$string = 'Hello World!';
if (strpos($string, 'Hello') !== false) {
echo 'True';
} ?>
ผลลัพธ์
True