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
Answer from Kendall Hopkins on Stack Overflowstr_starts_with but for arrays
str_starts_with slower than userland
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
Use strpos():
if (strpos($string2, 'http') === 0) {
// It starts with 'http'
}
Remember the three equals signs (===). It will not work properly if you only use two. This is because strpos() will return false if the needle cannot be found in the haystack.
Hi,
I am building a phone system where I have a list of extensions that can be pressed. For example we can have an array like this:
$options = array(1 => 'play_story', 10 => 'call_mom', 200 => 'call_pop', 3 => 'play_story')
So if someone presses 1 it could be they are only pressing 1 or they could be pressing 10 so I need to wait to see if they press a 0 or not.. If someone presses 2 then the only option is for them to press 200 (though it could be they will try 201 which is invalid). As soon as I get 200 I know it's the only valid option. If they press 3 right away since I know it's the only option I don't have to wait for any more digits.
I need a way to be able to see if 1) What they entered is even valid. So say for instance if someone presses 4 or press 21 I know right away it's not valid since the array does not have any number that starts or is 4 or 21. I have found str_starts_with but that seems to match a specific string. Is there anything like str_starts_with that would check the array key or I would need to loop through each one, each time?
TIA.
Dovid