PHP: Split string by first occurrence of a character.

This is a PHP tutorial on how to split a string by the first occurrence of a given character. This can be particularly handy in cases where the character in question may exist more than once.

Let’s take a look at the following example:

In the PHP code above:

  1. We created a simple PHP string. This string contains two colon characters. In this case, we want to split the year from the rest of the string. If we use the explode function, we will get three pieces. However, we only want two.
  2. By using the PHP function strpos, we can get the first occurrence of a substring. In this case, we want to get the first occurrence of the colon character.
  3. Once we have the position of the first colon character, we can use the substr function.
  4. We get the first part of the string by providing the substr function with three parameters: Our original string, the position that we want to start from and the position that we want to end at. By providing it with the position of our colon character, we effectively tell the substr function that we only want the “2019” segment of our string. In the example above, the “:” character starts at 4.
  5. Finally, we get the second half of the string by using the position of our first-occurring colon character as the starting position.

To clean up the second string and omit the first colon, you can do something like this:

Above, we used the trim function to remove any whitespace and we set the start position to +1 so that the substr function doesn’t return the first occurrence.

Hopefully, this example helped solve whatever problem you were having!

Facebook Comments