Replacing words in a text all with different replacement

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

mrkite
Forum Contributor
Posts: 104
Joined: Tue Sep 11, 2007 4:19 am

Post by mrkite »

Stryks wrote: I'm just not a fan of using global. Again, this is just a personal style thing. When I get to the point of using global I tend to stop and ask myself if I'm not going at things the wrong way.
Me neither. I'm of the opinion that preg_replace_callback should have a userdata argument.
User avatar
Stryks
Forum Regular
Posts: 746
Joined: Wed Jan 14, 2004 5:06 pm

Post by Stryks »

I guess you could always come at it from a different angle with an implementation like this ...

Code: Select all

class regexReplace {
	
	private static $replace;
	
	public static function execute($pattern, $subject, $replace) {
		self::$replace = $replace;
		return preg_replace_callback($pattern, array('self', 'get_insert_callback'), $haystack);        
	}

	private function get_insert_callback($matches) {
		if(!is_array(self::$replace)) return self::$replace;
		$result = current(self::$replace);
		next(self::$replace);    
		return $result;
	}
}
Called with ...

Code: Select all

$original="It's a nice day in a nice way.";

$values=array('glorious','wonderful','marvelous','good','grand');
shuffle($values);

echo regexReplace::execute('/\\bnice\\b/i', $original, $values);
I haven't really tested it all that much, and it could be cleaner, but it gets rid of the global and handles userdata. No doubt it introduces other concerns, but yeah ...
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post by Kieran Huggins »

Don't curse, recurse! (lol... I slay me.)

Code: Select all

$original = "It's a nice day in a nice way.";
$values = array('glorious','wonderful','marvelous','good','grand'); 

function r($needle,$replacement_needles,$haystack){
	$haystack = preg_replace('/\b'.$needle.'\b/i',$replacement_needles[array_rand($replacement_needles)],$haystack,1);
	if (strpos($haystack,$needle)) $haystack = r($needle,$replacement_needles,$haystack);
	return $haystack;
}

echo r('nice',$values,$original);
User avatar
Stryks
Forum Regular
Posts: 746
Joined: Wed Jan 14, 2004 5:06 pm

Post by Stryks »

See ... now this is why I love this place.

Something right in front of me that I was totally unaware of. Wheres that little bowing smiley when you need him.

The only thing I'd do differently is still to shuffle the array before use. array_rand() results always seem to return certain values often and some very rarely. That could just be me though.

Apart from that, sweet as. 8)
Post Reply