w3resource

PHP String Exercises: Remove a part of a string from the beginning

PHP String: Exercise-15 with Solution

Write a PHP script to remove a part of a string from the beginning.

Sample string : '[email protected]'

Visual Presentation:

PHP String Exercises: Remove a part of a string from the beginning

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:

Flowchart: Remove a part of a string from the beginning

PHP Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a PHP script to print the next character of a specific character.
Next: Write a PHP script to get a hex dump of a string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/php-exercises/php-string-exercise-15.php