Page 2 of 2

Posted: Sat Oct 13, 2007 1:16 am
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.

Posted: Sun Oct 14, 2007 3:13 am
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 ...

Posted: Sun Oct 14, 2007 3:45 am
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);

Posted: Sun Oct 14, 2007 6:14 am
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)