Me neither. I'm of the opinion that preg_replace_callback should have a userdata argument.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.
Replacing words in a text all with different replacement
Moderator: General Moderators
I guess you could always come at it from a different angle with an implementation like this ...
Called with ...
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 ...
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;
}
}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);
- Kieran Huggins
- DevNet Master
- Posts: 3635
- Joined: Wed Dec 06, 2006 4:14 pm
- Location: Toronto, Canada
- Contact:
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);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.
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.