How to check if a string starts with "_" in PHP?

php

Question

Example: I have a $variable = "_foo", and I want to make absolutely sure that $variable does not start with an underscore "_". How can I do that in PHP? Is there some access to the char array behind the string?

1
53
8/4/2015 3:14:56 PM

Accepted Answer

You might check out the substr function in php and grab the first character that way:

http://php.net/manual/en/function.substr.php

if (substr('_abcdef', 0, 1) === '_') { ... }
103
12/25/2009 9:54:12 PM

$variable[0] != "_"

How does it work?

In PHP you can get particular character of a string with array index notation. $variable[0] is the first character of a string (if $variable is a string).


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon