How i can replace/remove exact match word from string, an example string
$string = 'Hello world, command data test com';
How to remove com ( exact match from the string ) but to don't remove the com from command to
You need to use preg_replace. Basically preg_replace()
searches the subject for pattern matches and replaces them with the replacement.
<?php
$string = 'Hello world, command data test com';
$string = preg_replace('/\bcom\b/', '', $string);
echo $string;
?>
Explanation: Above example pattern is explained below
\b: Match a word boundary.
com: Text to match.
For more Special Character Definitions check this
Short version:
join(' ',array_diff(explode(' ', $string), ['com']));
Explanation:
explode(' ', $string)
splits your string into an array of wordsarray_diff($words, ['com'])
removes the elements on the second array from the first array. So in case the array of $words
contains the word com
, it will be removedjoin(' ', $words)
concats all the strings in the $words
array, dividing each word from each other with a space.Full snippet:
<?php
$string = 'Hello world, command data test com';
$words = explode(' ', $string);
$words = array_diff($words, ['com']);
$string = join(' ', $words);