06/04/2021, 14:46
Hàm substr_compare() trong PHP - PHP Function
Code echo substr_compare("abcde", "bc", 1, 2) . '<br>'; // 0 echo substr_compare("abcde", "de", -2, 2) . '<br>'; // 0 echo substr_compare("abcde", "bcg", 1, 2) . '<br>'; // 0 echo substr_compare("abcde", "BC", 1, 2, true) . '<br>'; // 0 echo ...
Hàm substr_compare() có tác dụng so sánh 1 đoạn của chuỗi này với một chuỗi khác. Ta có thể hiểu rằng hàm sẽ lấy một đoạn chuỗi ban đầu rồi đem so sánh chuỗi con đó với một chuỗi khác.
Cú pháp
Cú pháp: substr_compare($main_str, $str, $pos, $lent);
Trong đó:
$main_strlà chuỗi thứ nhất.$strlà chuỗi thứ 2.$poslà vị trí bắt đầu so sánh ở$main_str.$lentlà số kí tự tính từ$poscủa chuỗi$main_strsẽ đem so sánh với$str.
Ví dụ
Đây là ví dụ mình tham khảo trên trang chủ php.net:
Code
echo substr_compare("abcde", "bc", 1, 2) . '<br>'; // 0
echo substr_compare("abcde", "de", -2, 2) . '<br>'; // 0
echo substr_compare("abcde", "bcg", 1, 2) . '<br>'; // 0
echo substr_compare("abcde", "BC", 1, 2, true) . '<br>'; // 0
echo substr_compare("abcde", "bc", 1, 3) . '<br>'; // 1
echo substr_compare("abcde", "cd", 1, 2) . '<br>'; // -1
echo substr_compare("abcde", "abc", 5, 1); // warning
Kết quả
0 0 0 0 1 -1 Warning: substr_compare(): The start position cannot exceed initial string length in C:xampphtdocs estindex.php on line 8
Tham khảo: php.net
Nguồn: Zaidap.com.net