How to detect if a string starts with another string

I want to test if a string starts with another string. I thought it would be simple, but I am not getting the results I wanted.

if (substr($string_to_search, 0) == $string_to_search_for) {
echo 'string to search starts with string to search for'

But if $string_to_search = ‘sitepoint’, and $string_to_search_for = ‘site’, I am not given a match. What am I doing wrong?

I also tried:

if (strpos($haystack, $needle) === 0) {
 echo '$needle found to begin at 0 in string'				

But this is also giving me problems. It seems to match almost everything, I think because strpos is returning false and this might equal 0, meaning it always evaluates true. I thought using === might avoid this, so maybe another error is taking place.

Do I need to use regex for this or is this possible with php functions?

You need the length on your substr.

substr($str_to_search,0,strlen($str_to_search_for)) === $string_to_search_for

substr($string,0) will just give you $string again. (Start at 0, go to end of string)

1 Like

If you were using == then yes, that would definitely be the case, but since you’re using === PHP knows that false != 0 so you’re not having that problem, it must be something else. Have you checked the values of $haystack and $needle?

1 Like

Scallio, you were right. I mixed up the needle and haystack. I even double checked it, so I thought that couldn’t be it, since I have made that error before. I double checked again after your comment. Just simple error on my part.

Thanks Starlion for showing me how to use substr effectively in this case.

Yes, PHP has a few functions that are similar but have different argument ordering. I still get confused and have to often check the docs just to be sure even now after many years.

I had that too, until @Salathe pointed out to me that functions to search in arrays are always needle, haystack whereas functions to search in strings are always haystack, needle. Once you know that it’s not that hard anymore :slight_smile: