Navigation

Php

PHP String Starts With: Complete Guide with 5 Proven Methods

Learn 5 proven methods to check if PHP string starts with specific characters. Complete guide with code examples, performance tips, and best practices for developers.

Checking if a PHP string starts with specific characters is one of the most common string operations in web development. Whether you're validating URLs, processing file names, or filtering data, knowing how to efficiently check string beginnings is essential for every PHP developer.

Table Of Contents

What Does "PHP String Starts With" Mean?

PHP string starts with refers to checking whether a string begins with a particular substring or character sequence. This operation is crucial for data validation, routing, file processing, and countless other programming scenarios.

$string = "Hello World";
// Check if string starts with "Hello"
// Result: true

Method 1: str_starts_with() Function (PHP 8+)

The most modern and efficient way to check if a PHP string starts with a substring is using the str_starts_with() function introduced in PHP 8.0.

$string = "https://example.com";

// Check if string starts with "https"
if (str_starts_with($string, "https")) {
    echo "Secure URL detected!";
}

// Case-sensitive check
$text = "Hello World";
var_dump(str_starts_with($text, "hello")); // false
var_dump(str_starts_with($text, "Hello")); // true

Advantages:

  • Clean, readable syntax
  • Built-in function optimized for performance
  • Returns boolean directly
  • Case-sensitive by default

Method 2: substr() Method (All PHP Versions)

The substr() function is the most compatible method for checking if a PHP string starts with specific characters across all PHP versions.

$string = "welcome.txt";
$prefix = "welcome";

// Check if string starts with prefix
if (substr($string, 0, strlen($prefix)) === $prefix) {
    echo "String starts with 'welcome'";
}

// One-liner function
function startsWith($string, $prefix) {
    return substr($string, 0, strlen($prefix)) === $prefix;
}

// Usage
if (startsWith("document.pdf", "document")) {
    echo "Document file detected!";
}

Pro Tips:

  • Always use === for exact comparison
  • strlen($prefix) gets the exact length to check
  • Works with any PHP version

Method 3: strpos() Method

Using strpos() to check if a PHP string starts with a substring is another reliable approach:

$string = "JavaScript is awesome";

// Check if string starts with "JavaScript"
if (strpos($string, "JavaScript") === 0) {
    echo "String starts with JavaScript";
}

// Helper function
function stringStartsWith($haystack, $needle) {
    return strpos($haystack, $needle) === 0;
}

// Example usage
$urls = [
    "https://secure-site.com",
    "http://regular-site.com",
    "ftp://file-server.com"
];

foreach ($urls as $url) {
    if (stringStartsWith($url, "https")) {
        echo "$url is secure\n";
    }
}

Important Notes:

  • Must use === 0 (not == 0) to avoid false positives
  • Returns false if substring not found
  • Case-sensitive comparison

Method 4: Regular Expressions with preg_match()

For complex pattern matching, use regex to check if a PHP string starts with specific patterns:

$string = "Product_ABC123";

// Check if string starts with "Product_"
if (preg_match('/^Product_/', $string)) {
    echo "Valid product code format";
}

// Multiple patterns
$emails = [
    "admin@example.com",
    "user@domain.org",
    "support@company.net"
];

foreach ($emails as $email) {
    if (preg_match('/^(admin|support)@/', $email)) {
        echo "$email is a system email\n";
    }
}

// Case-insensitive check
if (preg_match('/^hello/i', "Hello World")) {
    echo "String starts with 'hello' (case-insensitive)";
}

Regex Benefits:

  • Pattern-based matching
  • Case-insensitive options with /i flag
  • Complex pattern support
  • Multiple alternatives with |

Method 5: Custom Case-Insensitive Function

Create a flexible function for PHP string starts with operations that handles case sensitivity:

function startsWithIgnoreCase($string, $prefix, $ignoreCase = false) {
    if ($ignoreCase) {
        return stripos($string, $prefix) === 0;
    }
    return strpos($string, $prefix) === 0;
}

// Usage examples
$text = "WELCOME TO PHP";

// Case-sensitive (false)
var_dump(startsWithIgnoreCase($text, "welcome", false));

// Case-insensitive (true) 
var_dump(startsWithIgnoreCase($text, "welcome", true));

Performance Comparison

Here's how different methods perform for PHP string starts with operations:

Method PHP Version Performance Use Case
str_starts_with() 8.0+ Fastest Modern applications
substr() All Fast Legacy compatibility
strpos() All Fast General purpose
preg_match() All Slower Complex patterns

Real-World Examples

1. URL Validation

function isSecureUrl($url) {
    return str_starts_with($url, "https://");
}

// Usage
$links = ["https://secure.com", "http://insecure.com"];
foreach ($links as $link) {
    echo $link . " is " . (isSecureUrl($link) ? "secure" : "not secure") . "\n";
}

2. File Type Detection

function getFileType($filename) {
    $imageTypes = ["jpg", "png", "gif", "webp"];
    $docTypes = ["pdf", "doc", "docx"];
    
    foreach ($imageTypes as $type) {
        if (str_ends_with(strtolower($filename), ".$type")) {
            return "image";
        }
    }
    
    foreach ($docTypes as $type) {
        if (str_ends_with(strtolower($filename), ".$type")) {
            return "document";
        }
    }
    
    return "unknown";
}

3. Route Matching

function matchRoute($uri, $pattern) {
    // Remove leading slash for consistency
    $uri = ltrim($uri, '/');
    $pattern = ltrim($pattern, '/');
    
    return str_starts_with($uri, $pattern);
}

// Usage
$currentUri = "/api/users/123";
if (matchRoute($currentUri, "/api/")) {
    echo "API endpoint detected";
}

Best Practices

1. Choose the Right Method

// For PHP 8+
if (str_starts_with($string, $prefix)) { /* ... */ }

// For older PHP versions  
if (substr($string, 0, strlen($prefix)) === $prefix) { /* ... */ }

2. Handle Edge Cases

function safeStartsWith($string, $prefix) {
    // Handle null/empty inputs
    if (empty($string) || empty($prefix)) {
        return false;
    }
    
    return str_starts_with($string, $prefix);
}

3. Create Reusable Functions

class StringHelper {
    public static function startsWith($string, $prefix, $caseSensitive = true) {
        if (!$caseSensitive) {
            return stripos($string, $prefix) === 0;
        }
        
        return PHP_VERSION_ID >= 80000 
            ? str_starts_with($string, $prefix)
            : substr($string, 0, strlen($prefix)) === $prefix;
    }
}

Common Pitfalls to Avoid

1. Using == Instead of ===

// Wrong - can cause false positives
if (strpos($string, $prefix) == 0) { }

// Correct - exact comparison
if (strpos($string, $prefix) === 0) { }

2. Forgetting Case Sensitivity

// This will fail for "HELLO world"
if (str_starts_with("HELLO world", "hello")) { }

// Better approach
if (str_starts_with(strtolower("HELLO world"), strtolower("hello"))) { }

Conclusion

Mastering PHP string starts with operations is essential for effective string manipulation in PHP. Whether you use the modern str_starts_with() function or stick with compatible methods like substr() and strpos(), choose the approach that best fits your PHP version and performance requirements.

Remember to handle edge cases, consider case sensitivity, and always test your string validation logic thoroughly. With these techniques, you'll be able to efficiently check string beginnings in any PHP application.

Share this article

Add Comment

No comments yet. Be the first to comment!

More from Php