This article demonstrates how to remove a substring from the beginning of a string in PHP.

1. Using substr() function

The substr() function extracts a portion of the string as specified by the offset and length parameters. If length is omitted, then substr() returns the substring starting from offset until the string’s end. You can use the substr() function as follows to remove a substring starting at the beginning of the string.

You might want to check if the string starts with the substring first. This can be done using the strpos() function, which returns the position of the first occurrence of a substring in a string.

Download  Run Code

2. Using preg_replace() function

Alternatively, you can use preg_replace() function to remove a substring from the beginning of a string. If your substring is $prefix, you can use the search pattern "/^{$prefix}/" with the empty string ("") as the replacement string. Here, {$prefix} is the interpolated string within the double-quotes, and the caret symbol (^) matches the beginning of the string. Note that the performance of this function will be slower than the substr() function.

Download  Run Code

3. Using str_replace() function

If you need to find and remove all occurrences of a substring in a string, you can use the str_replace() function. It replaces all occurrences of the search string with the replacement string. In order to remove all occurrences of the search string from the input text, you can use the empty string ("") as the replacement string.

Download  Run Code

That’s all about removing a substring from the beginning of a string in PHP.