Code Snippet: Test if String Starts With Certain Characters in PHP 
Tuesday, April 21, 2020, 11:08 PM
A: 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;
}

Comments

Add Comment
Fill out the form below to add your own comments.









Insert Special:
:o) :0l







Moderation is turned on for this blog. Your comment will require the administrators approval before it will be visible.