Using str_replace ...
A simple approach is to use str_replace or str_ireplace , which can take an array of "needles" (things to look for), appropriate replacements, and an array of "haystacks" (things to work).
$haystacks=array( "The quick brown fox", "jumps over the ", "lazy dog" ); $needles=array( "the", "lazy", "quick" ); $result=str_ireplace($needles, "", $haystacks); var_dump($result);
It creates
array(3) { [0]=> string(11) " brown fox" [1]=> string(12) "jumps over " [2]=> string(4) " dog" }
As an aside, a quick way to clear the trailing spaces that this leaves is to use array_map to call trim for each element
$result=array_map("trim", $result);
The disadvantage of using str_replace is that it replaces matches found in words, not just whole words. To solve this problem, we can use regular expressions ...
Use preg_replace
The preg_replace approach looks very similar to the above, but the needles are regular expressions, and we check the word boundary at the beginning and end of the match using \ b
$haystacks=array( "For we shall use fortran to", "fortify the general theme", "of this torrent of nonsense" ); $needles=array( '/\bfor\b/i', '/\bthe\b/i', '/\bto\b/i', '/\bof\b/i' ); $result=preg_replace($needles, "", $haystacks);
Paul dixon
source share