Problem:
You have a string. You want to check if that string starts with another string or a character.
Solution:
Using strops() function, you can find the first occurrence of a string inside another string. The strpos() function finds the position of the first occurrence of a string/character in another string. See the example below-
<?php $haystack = "HTML is the language of web."; $needle = "HTML"; echo strpos($haystack, $needle, 0)=== 0 ? "Yes, the string begins with $needle.": "No, the string doesn't begin with $needle."; ?>
[wpdm_file id=110]
Output:
Yes, the string begins with HTML.
Line 2 | This is the string we’ll serach into |
Line 3 | This(HTML) is the string that we’ll find. |
Line 4 | The strops() function will search the $needle(HTML) in the $haystack. The function founds the $needle in the first position and returns 0, so the ternary operator prints “Yes, the string begins with HTML. ”. |
Notes
We used identical operator(===) to make sure that the $needle exists at the beginning of the $haystack. Not only the condition above won’t return 0 if the $needle is existed in other positions other than the first one, but also, If the function return false if the $needle is not existed in the $haystack. But, the identical operator(===) will ensure the $needle is in the beginning of the $haystack.