Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Check if a string starts with given word in PHP
In PHP, you can check if a string starts with a specific word or substring using various methods. The most common approaches include using substr(), strpos(), or the newer str_starts_with() function (PHP 8+).
Using Custom Function with substr()
Create a function that compares the beginning of a string with the specified substring ?
<?php
function begnWith($str, $begnString) {
$len = strlen($begnString);
return (substr($str, 0, $len) === $begnString);
}
if(begnWith("pqrstuvwxyz", "pqr")) {
echo "True! It begins with 'pqr'!";
} else {
echo "False! It doesn't begin with 'pqr'!";
}
?>
True! It begins with 'pqr'!
Using strpos()
Check if the substring appears at position 0 ?
<?php
function startsWithStrpos($str, $prefix) {
return strpos($str, $prefix) === 0;
}
$text = "Hello World";
$prefix = "Hello";
if(startsWithStrpos($text, $prefix)) {
echo "String starts with '$prefix'";
} else {
echo "String does not start with '$prefix'";
}
?>
String starts with 'Hello'
Using str_starts_with() (PHP 8+)
The modern approach using PHP's built-in function ?
<?php
$text = "Programming with PHP";
$prefix = "Programming";
if(str_starts_with($text, $prefix)) {
echo "Text starts with '$prefix'";
} else {
echo "Text does not start with '$prefix'";
}
?>
Text starts with 'Programming'
Comparison
| Method | PHP Version | Performance | Case Sensitive |
|---|---|---|---|
substr() |
All versions | Good | Yes |
strpos() |
All versions | Fast | Yes |
str_starts_with() |
PHP 8.0+ | Optimized | Yes |
Conclusion
Use str_starts_with() for PHP 8+ projects as it's purpose-built and optimized. For older PHP versions, strpos() === 0 is the fastest approach for checking string prefixes.
Advertisements
