Tuesday, April 21, 2020, 11:08 PM
Posted by Administrator
A: We can test if a certain string is the exact start of another string:Posted by Administrator
<?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;
}
add comment
( 185 views )
| permalink
| ( 3 / 583 )