I'm trying to find out if the second character in a string is a space. So if I have this:
"a brown fox"
and
"hello world"
How can I flag that the first string has a space at the 2nd position but the second string doesn't?
I'm trying to find out if the second character in a string is a space. So if I have this:
"a brown fox"
and
"hello world"
How can I flag that the first string has a space at the 2nd position but the second string doesn't?
I can think of multiple ways to do this, for example
if($string[1] == " ") {
//$string's 2nd character is a space
}
The [1]
captures the 2nd letter of the string, because it acts as an array and arrays start with the key 0
.
If you get an error saying the string is not an array, or invalid index etc, then you may need to split your string into an array for this first one to work.
if(str_split($string)[1] == " ") {
//$string's 2nd character is a space
}
substr()
Similar to the first example, you could also use substr()
:
if(substr($string, 1, 1) == " ") {
//$string's 2nd character is a space
}
strpos()
Similar again, you could use strpos()
if(strpos("a brown fox", " ") == 1) {
//$string's 2nd character is a space
}
preg_match()
You could also use regex if you wanted to
if (preg_match('/^. /', $string)) {
//$string's 2nd character is a space
}
Pattern breakdown:
^
asserts position at start of a line.
matches any character (except for line terminators)
matches the character literallyexplode()
Another, admittedly less simple way, would be to use explode()
to break the string at spaces, and then count how long the the string is before the first space.
$string_parts = explode(" ", $string);
if(strlen($string_parts[0]) <= 1) {
//$string's 2nd character is a space
}
This is useful if you already planned on breaking your string into multiple parts.