Page 1 of 1

[Solved]str_replace - Opposite/Reverse of?

Posted: Thu Feb 03, 2011 2:40 am
by christh
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

Re: str_replace - Opposite/Reverse of?

Posted: Thu Feb 03, 2011 5:55 am
by Darhazer

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?

Posted: Mon Feb 07, 2011 12:35 pm
by christh
Hey Darhazer

Many thanks for that - does just what I wanted

Cheers

Chris

Re: [Solved]str_replace - Opposite/Reverse of?

Posted: Mon Feb 07, 2011 12:56 pm
by AbraCadaver
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]);