1

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?

Mike Green
  • 51
  • 1
  • 6
  • `$string[1]` will return the second character, then you only have to compare it to space... – Danielius Jul 26 '18 at 18:07
  • 1
    Possible duplicate of [Getting the first character of a string with $str\[0\]](https://stackoverflow.com/questions/1972100/getting-the-first-character-of-a-string-with-str0) – Danielius Jul 26 '18 at 18:10

1 Answers1

2

I can think of multiple ways to do this, for example

Accessing string as an array

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
}

Using substr()

Similar to the first example, you could also use substr():

if(substr($string, 1, 1) == " ") {
    //$string's 2nd character is a space
}

Using strpos()

Similar again, you could use strpos()

if(strpos("a brown fox", " ") == 1) {
    //$string's 2nd character is a space
}

Using 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 literally

Using explode()

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.

GrumpyCrouton
  • 8,486
  • 7
  • 32
  • 71