How to check if a string starts with a given substring in PHP?
Hello everyone! I'm a beginner in PHP and writing a small script for URL processing. I need to check if a string starts with a specific prefix, for example, "https://" or "/admin/". In other languages, I've seen functions like startsWith(), but in PHP, there doesn't seem to be one.
I tried using strpos(), but it returns a position, not a boolean value. I had to write a workaround:
$url = "https://example.com";
if (strpos($url, "https://") === 0) {
echo "Starts with https";
}
This works, but it looks ugly. I have to constantly write === 0, which is easy to forget or confuse with !== false. Is there a more elegant way? Maybe a built-in function or a short construct?
I'd appreciate code examples and an explanation of how it works. Thanks!
No answers yet.
Log in to leave an answer
Blogs
Integration Testing JavaScript with Docker: A Complete Guide
Concurrency and Multithreading in Swift: Advanced Techniques
From Seconds to Years: Calculating Relative Time in C# Correctly
Rust and Hexagonal Architecture: Clean Code Without Compromises