Search  


Code Snippet: Test if String Starts With Certain Characters in PHP 
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:

<?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 ( 184 views )   |  permalink   |  $star_image$star_image$star_image$star_image$star_image ( 3 / 583 )

<<First <Back | 1215 | 1216 | 1217 | 1218 | 1219 | 1220 | 1221 | 1222 | 1223 | 1224 | Next> Last>>







Share CertificationPoint & Stay Informed Socially About EduTech?