Hi
I hope you are all well.
Is there a function or a way to use str_replace to keep the words in an array rather than replace them from the target string - Effectively replace all no array content?
ie -
array = "fox", "dog"
string = "the quick brown fox jumps over the lazy dog"
result = "fox dog"
Thanks in advance.
Chris
[Solved]str_replace - Opposite/Reverse of?
Moderator: General Moderators
[Solved]str_replace - Opposite/Reverse of?
Last edited by christh on Mon Feb 07, 2011 12:35 pm, edited 1 time in total.
Re: str_replace - Opposite/Reverse of?
Code: Select all
function cleanup($string, $allowedWords) {
$input = explode(' ', $string);
$result = array();
foreach ($input as $word) {
if (in_array($word, $allowedWords)) {
$result[] = $word;
}
}
return implode(' ', $result);
}
$array = array("fox", "dog");
$string = "the quick brown fox jumps over the lazy dog";
echo cleanup($string, $array);Re: str_replace - Opposite/Reverse of?
Hey Darhazer
Many thanks for that - does just what I wanted
Cheers
Chris
Many thanks for that - does just what I wanted
Cheers
Chris
- AbraCadaver
- DevNet Master
- Posts: 2572
- Joined: Mon Feb 24, 2003 10:12 am
- Location: The Republic of Texas
- Contact:
Re: [Solved]str_replace - Opposite/Reverse of?
Rather than replace what isn't wanted, why not return what is wanted?
Code: Select all
preg_match_all('/' . implode('|', $array) . '/', $string, $matches);
$result = implode(' ', $matches[0]);mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.