Remove a substring from beginning of a string in PHP
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php function remove_prefix($text, $prefix) { if (strpos($text, $prefix) === 0) { return substr($text, strlen($prefix)); } return $text; } $text = "Pi~3.14"; $prefix = "Pi"; $result = remove_prefix($text, $prefix); echo $result; /* Output: ~3.14 */ ?> |
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
<?php $text = "Pi~3.14"; $prefix = "Pi"; $result = preg_replace("/^{$prefix}/", "", $text); echo $result; /* Output: ~3.14 */ ?> |
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
<?php $text = "Pi~3.14"; $prefix = "Pi"; $result = str_replace($prefix, "", $text); echo $result; /* Output: ~3.14~ */ ?> |
That’s all about removing a substring from the beginning of a string in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)