Skip to main content
Home / Code Snippets / PHP / Test if String Starts With Certain Characters in PHP

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;
}