substr_compare

funkcja

Porównuje fragment ciągu haystack od podanego offsetu z ciągiem needle, opcjonalnie bez uwzględniania wielkości liter.

substr_compare(string $haystack, string $needle, int $offset, ?int $length = null, bool $case_insensitive = false): int

substr_compare porównuje fragment $haystack zaczynający się od pozycji $offset z ciągiem $needle. Zwraca 0 gdy są równe, wartość ujemną gdy fragment jest mniejszy, a dodatnią gdy większy — analogicznie do strcmp. Parametr $case_insensitive = true sprawia, że porównanie ignoruje wielkość liter. To wydajniejsza alternatywa dla substr() + strcmp(), bo nie tworzy tymczasowego podciągu.

<?php
declare(strict_types=1);

var_dump(substr_compare('hello world', 'world', 6));               // wynik: int(0)
var_dump(substr_compare('hello world', 'WORLD', 6, null, true));   // wynik: int(0)
var_dump(substr_compare('hello world', 'xyz', 6));                 // wynik: int(-1)
📘 Naucz się w lekcji →