To remove a string from another string variable in php, the easiest way is to use the php str_replace() function.
$string = "This is a string.";
$string_without_his = str_replace("his","", $string);
echo $string_without_his;
// Output:
T is a string.
You can also use the preg_replace() function to use regex to remove strings from string variables in php.
$string = "This is a string.";
$string_without_his = preg_replace("/his+/","", $string);
echo $string_without_his;
// Output:
T is a string.
When working with string variables in php, being able to manipulate your variables easily is important. There are a number of built in string methods which allow us to get information and change string variables.
One such function which is very useful is the string str_replace() function. With str_replace(), we can create a new string where the specified value is replaced by another specified value.
We can use the str_replace() function to remove strings from a string.
To remove a string from a string, we can use the str_replace() function as shown in the following php code.
$string = "This is a string.";
$string_without_his = str_replace("his","", $string);
echo $string_without_his;
// Output:
T is a string.
Removing Parts of Strings in php with preg_replace()
Another function we can use to remove substrings from string variables in a php string is the php preg_replace() function.
preg_replace() performs a regular expression (regex) search on a string or array of strings, and returns a string or an array of strings where all matches of the regex pattern or list of regex patterns found are replaced with substrings.
Below is an example of how to remove part of a string using preg_replace() in php.
$string = "This is a string.";
$string_without_his = preg_replace("/his+/","", $string);
echo $string_without_his;
// Output:
T is a string.
Using the str_replace() function to Make Replacements in Strings in php
Below are a few more examples of how you can use the str_replace() function to make replacements in strings or remove parts of strings in php.
For example, if we want to replace underscores with spaces, we can do the following.
$string_with_underscores = "This_is_a_string.";
$string_with_spaces = str_replace("_"," ", $string_with_underscores);
echo $string_with_spaces ;
// Output:
This is a string.
If we want to remove characters from a string, we can do so easily in the following php code.
$string_with_spaces = "This is a string.";
$string_with_periods = str_replace(" ",".", $string_with_spaces);
echo $string_with_periods;
// Output:
This_is_a_string.
Hopefully this article has been useful for you to learn how to remove a string from a string in php.