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:
//Example PHP string. $string = '2019: Example: This is a string.'; //Get the first occurrence of a character. $strpos = strpos($string, ':'); //var_dump returns "int 4" var_dump($strpos); //Get the first half of the string $stringSplit1 = substr($string, 0, $strpos); var_dump($stringSplit1); //2019 //Get the second half of the string $stringSplit2 = substr($string, ($strpos)); var_dump($stringSplit2); //: Example: This is a string.
In the PHP code above:
- 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.
- 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.
- Once we have the position of the first colon character, we can use the substr function.
- 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.
- 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:
//Use trim to remove whitespace and set the start position //to +1 $stringSplit2 = trim(substr($string, ($strpos + 1)));
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!