OneBite.Dev - Coding blog in a bite size

Remove A Substring From A String In PHP

Code snippet for how to Remove A Substring From A String In PHP with sample and detail explanation

In numerous instances during coding, developers often need to remove a substring from a string. PHP, a popular scripting language, provides an easy and efficient method to achieve this. This article will provide a detailed understanding of how to remove a substring from a string in PHP.

Code snippet for Removing Substring

Let’s start with the actual code representation of the substring removal.

<?php
    $mainString = 'Hello World!';
    $subString = ' World';
    $resultString = str_replace($subString, '', $mainString);
    echo $resultString;
?>

In the instruction given above, we will obtain an output: “Hello!”

Code Explanation for Removing Substring

Let’s break down the code and understand the minor details.

We start by declaring a string variable $mainString with the value ‘Hello World!‘. This is the main string from which we’ll remove a specific substring.

Next, we declare another string variable $subString with the value ’ World’. This is the substring which we need to remove from our main string.

Then comes the core function: str_replace(). This is a built-in function in PHP which is used to replace some characters with some other characters in a string. The syntax of using str_replace function in PHP is:

str_replace(find, replace, string, count)

Here, the find parameter specifies the value to find, replace parameter specifies the value to replace and string parameter specifies the string to search and replace in. The fourth optional parameter count will hold the number of replacements done.

In this case, we are replacing $subString with ‘’(empty) in $mainString.

Finally, we print the $resultString using echo. Since ’ World’ is removed from ‘Hello World!’, we are left with ‘Hello!’, which is the output.

Through this method, you can efficiently remove a specific substring from a string in PHP. Don’t forget to test the codes in your own script to understand the concept more precisely.

php