PHP Checking if a string starts with #
I know theres functions for this but the ones i've tried wont work with the character '#' The one im using right now is
function startsWithChar($ne开发者_StackOverflowedle, $haystack)
{
return ($needle[0] === $haystack);
}
and it returns false when I try to check for '#'.
Does anyone know a function that works with the '#' character?
EDIT: I noticed that the function works, the problem is that I'm trying to do this using GET. Apparantly the string gets ignored when a GET begins with # (search.php?query=#asd). Do you know a workaround for this?
Are you confusing your needle and your haystack?
function startsWithChar($needle, $haystack) {
return ($haystack[0] === $needle);
}
$string1 = 'Test';
var_dump(startsWithChar('#',$string1)) ;
$string2 = '#Test';
var_dump(startsWithChar('#',$string2)) ;
Now that you've edited, it all becomes clear. The literal '#' character in the URL is interpreted as the end of the query string and the start of the fragment, so your script is getting just "search.php?query=". Use %23 instead. See http://en.wikipedia.org/wiki/Percent_encoding for details.
How about this:
function startsWithChar($haystack, $needle){
return mb_strpos($haystack, $needle) === 1;
}
精彩评论