PHP String Exercises: Remove a part of a string from the beginning
15. Remove Part of String from Beginning
Write a PHP script to remove a part of a string from the beginning.
Sample string : '[email protected]'
Visual Presentation:

Sample Solution:
PHP Code:
<?php
$sub_string = 'rayy@';
// Define the substring to be checked at the beginning of the string.
$str = '[email protected]';
// Define the full string.
if (substr($str, 0, strlen($sub_string)) == $sub_string)
{
// Check if the substring matches the beginning of the string.
$str = substr($str, strlen($sub_string));
// If it matches, remove the substring from the beginning of the string.
}
echo $str."\n";
// Output the modified string.
?>
Output:
example.com
Explanation:
The above PHP code snippet checks if the substring `'rayy@'` is present at the beginning of the string `'[email protected]'`. It does this by using the `substr()` function to extract the substring from the start of the string and comparing it with the given substring. If they match, it removes the substring from the beginning of the string using `substr()` again. Finally, it outputs the modified string `'example.com'`. Essentially, this code removes the prefix `'rayy@'` from the string `'[email protected]'` if it exists at the beginning.
Flowchart:

For more Practice: Solve these Related Problems:
- Write a PHP script that removes the substring up to and including the first "@" character from an email address.
- Write a PHP function to drop the first few characters of a string based on a specified delimiter and return the remainder.
- Write a PHP program to remove the first word from a sentence and then output the remaining string.
- Write a PHP script to strip a given prefix from a string if it exists, otherwise return the original string.
Go to:
PREV : Print Next Character with Wrap-Around.
NEXT : Get Hex Dump of a String.
PHP Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.