Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string starts with a specified string? [duplicate]

Tags:

php

I'm trying to check if a string starts with http. How can I do this check?

$string1 = 'google.com'; $string2 = 'http://www.google.com'; 
like image 815
Andrew Avatar asked May 07 '10 18:05

Andrew


People also ask

How do you check if a string starts with a specified string?

The startsWith() method returns true if a string starts with a specified string. Otherwise it returns false . The startsWith() method is case sensitive.

How do you check if a string starts with a certain word in Java?

Java String startsWith() Method The startsWith() method checks whether a string starts with the specified character(s). Tip: Use the endsWith() method to check whether a string ends with the specified character(s).

How do you check if a variable is a specific string?

Use the typeof operator to check if a variable is a string, e.g. if (typeof variable === 'string') . If the typeof operator returns "string" , then the variable is a string. In all other cases the variable isn't a string. Copied!


1 Answers

PHP 8 or newer:

Use the str_starts_with function:

str_starts_with('http://www.google.com', 'http') 

PHP 7 or older:

Use the substr function to return a part of a string.

substr( $string_n, 0, 4 ) === "http" 

If you're trying to make sure it's not another protocol. I'd use http:// instead, since https would also match, and other things such as http-protocol.com.

substr( $string_n, 0, 7 ) === "http://" 

And in general:

substr($string, 0, strlen($query)) === $query 
like image 127
Kendall Hopkins Avatar answered Sep 19 '22 17:09

Kendall Hopkins