This article demonstrates how to extract everything after a certain character in a string in PHP.

1. Using substr() function

You can use the substr() function to extract a substring from a string. The two-arg substr() takes an input string and an offset indicating the starting position, and returns a substring starting from the offset until the end of the string. The idea is to find the position of the first occurrence of a given character within the string with strpos(), and then extract everything that follows it using substr().

Download  Run Code

 
Before extracting the substring, you might want to check the presence of that character in your string. Otherwise, the solution would return the input string with the first character skipped.

Download  Run Code

 
Take note of the !== operator. You must not use the != or ! operator here, since strpos() can return a falsey value even on success (index 0 is returned when the search string is located at the very start of the string). The extraction is done using the first occurrence of the character within the string. If you want to extract the substring after the last occurrence of a character, consider using the strrpos() function.

Download  Run Code

2. Using explode() function

Alternatively, you can split the string into two parts using the given character as a delimiter. The first string contains all characters before the delimiter, and the second string contains all characters after the delimiter. This can be done using the explode() function with the limit parameter set to 2, as shown below:

Download  Run Code

 
In the case of multiple occurrences of the character within the string, you can extract the substring after the character’s last occurrence by skipping the limit parameter, and returning its last element.

Download  Run Code

3. Using strtok() function

Finally, successive calls to the strtok() function will split a string into substrings according to the specified delimiter. The idea is to initially invoke the strtok() function using the given character as a delimiter, which returns the part of the string before the specified delimiter. Then, to obtain the remainder of the input string, make a subsequent call to strtok() with an empty string as the delimiter.

Download  Run Code

 
It should be noted that the above solution will not work if the delimiter is located at the beginning of the string. However, it can be used to extract the substring after the last occurrence of the character by making successive calls to strtok() with the specified character as delimiter.

Download  Run Code

 
However, strtok() will fail if the delimiter is a substring of the string with a length of two or more. It will tokenize the string when any one of the characters in the delimiter is found.

That’s all about extracting everything after a certain character in a string in PHP.