[Solved]str_replace - Opposite/Reverse of?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
christh
Forum Commoner
Posts: 25
Joined: Sat Jan 16, 2010 5:27 am

[Solved]str_replace - Opposite/Reverse of?

Post 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
Last edited by christh on Mon Feb 07, 2011 12:35 pm, edited 1 time in total.
User avatar
Darhazer
DevNet Resident
Posts: 1011
Joined: Thu May 14, 2009 3:00 pm
Location: HellCity, Bulgaria

Re: str_replace - Opposite/Reverse of?

Post 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);
christh
Forum Commoner
Posts: 25
Joined: Sat Jan 16, 2010 5:27 am

Re: str_replace - Opposite/Reverse of?

Post by christh »

Hey Darhazer

Many thanks for that - does just what I wanted

Cheers

Chris
User avatar
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?

Post 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]);
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.
Post Reply