This article demonstrates how to remove the part of a string that follows a substring (including the substring) in PHP.

1. Using substr() function

The idea is to find the index of the first occurrence of the substring in the string using the strpos() function. Then extract all characters before that index using the substr() function. This works since removing everything after a substring (including the substring) essentially results in the same string as extracting everything before it.

Download  Run Code

 
PHP 5.3 eliminates the need for calling the strpos() function by introducing a third parameter to the strstr() function. It is a boolean parameter that, if true, makes substr() return the part of the string before the substring’s first occurrence.

Download  Run Code

2. Using explode() function

Another option is to split the string with explode() using the substring as the delimiter. Since the explode() function returns an array of strings, the first item is the answer.

Download  Run Code

3. Using preg_replace() function

You can also use a regular expression to remove the part of a string that follows the given substring. This can be implemented as follows in PHP, using the preg_replace() function for regular expression matching. Here, .* matches zero or more occurrences of any character, and $ matches the end of the string.

Download  Run Code

4. Using substr_replace() function

Finally, if you need to remove the part of a string after the specified position, you can use the substr_replace() function. It replaces the input string, delimited by the offset and length parameters, with the replacement string. If the replacement string is an empty string ('') and the length parameter is omitted, then all characters starting from the offset position will be removed.

Download  Run Code

5. Using mb_strimwidth() function

Another option to remove the whole portion of a string after the specified position is using the mb_strimwidth() function. It works by truncating the string to the specified width.

Download  Run Code

That’s all about removing the part of a string that follows a substring in PHP.