Appearance
Delete particular word from string
In PHP, you can use the str_replace function to delete a particular word from a string. The function takes three arguments: the word or phrase to be replaced, the replacement word or phrase, and the string.
For example, to delete the word "apple" from the string "I have an apple", you would use the following code:
Example of using the str_replace function to delete a particular word from a string in PHP
php
<?php
$string = "I have an apple";
$string = str_replace("apple", "", $string);
echo $string; // Output: "I have an "
<div class="alert alert-info flex not-prose">Watch a video course Learn object oriented PHP
</div>
You can also use preg_replace function with regular expression to match and delete a particular word from a string.
Example of using preg_replace function with regular expression to match and delete a particular word from a string in PHP
php
<?php
$string = "I have an apple";
$string = preg_replace('/\bapple\b/', '', $string);
echo $string; // Output: "I have an "Note that this will only remove the exact word "apple" and not any word that contains the letters "apple" such as "applesauce" or "pineapple".