php check if string starts with code example
Example 1: php string starts with
//php check if first four characters of a string = http
substr( $http, 0, 4 ) === "http";
//php check if first five characters of a string = https
substr( $https, 0, 5 ) === "https";
Example 2: php string ends with
function stringStartsWith($haystack,$needle,$case=true) {
if ($case){
return strpos($haystack, $needle, 0) === 0;
}
return stripos($haystack, $needle, 0) === 0;
}
function stringEndsWith($haystack,$needle,$case=true) {
$expectedPosition = strlen($haystack) - strlen($needle);
if ($case){
return strrpos($haystack, $needle, 0) === $expectedPosition;
}
return strripos($haystack, $needle, 0) === $expectedPosition;
}
echo stringStartsWith("Hello World","Hell"); // true
echo stringEndsWith("Hello World","World"); // true
Example 3: Check if a String Starts With a Specified String in PHP
phpCopy<?php
$string = "Mr. Peter";
if(strncmp($string, "Mr.", 3) === 0){
echo "The string starts with the desired substring.";
}else
echo "The string does not start with the desired substring.";
?>
Example 4: Check if a String Starts With a Specified String in PHP
phpCopy<?php
$string = "Mr. Peter";
if(substr($string, 0, 3) === "Mr."){
echo "The string starts with the desired substring.";
}else
echo "The string does not start with the desired substring.";
?>
Example 5: Check if string starts with php
substr( $string_n, 0, 4 ) === "http"
Example 6: Check if a String Starts With a Specified String in PHP
phpCopy<?php
$string = "Mr. Peter";
if(strpos( $string, "Mr." ) === 0){
echo "The string starts with the desired substring.";
}else
echo "The string does not start with the desired substring.";
?>