We can test if a certain string is the exact start of another string:
<?php
function startsWith($string, $startString) {
$len = strlen($startString);
return (substr($string, 0, $len) === $startString);
}
// usage
echo startsWith("cat", "c"); // true
echo startsWith("dog", "x"); // false
?>
Testing the position in the string, making sure it’s at 0, works too:
function startsWith($string, $startString) {
return strpos($string, $startString) === 0;
}
The strncmp
function is also directly for this purpose:
function startsWith($string, $startString) {
return strncmp($string, $startString, strlen($startString)) === 0;
}
You can always RegEx too!
function startsWith($string, $startString) {
return preg_match('#^' . $startString . '#', $string) === 1;
}
If string contains no unicode characters, there is also simple method:
$a = “String”;
if($a[0] === “S”){
…
}
PHP 8 now supports three new methods for testing strings:
str_contains($string. $search)
str_starts_with($string. $search)
str_ends_with($string. $search)
// usage
str_contains(‘haystack’, ‘sta’); // true
str_starts_with(‘haystack’, ‘h’); // true
str_ends_with(‘haystack’, ‘x’); // false