
PHP Code Stuff
What's here?
Nothing special, just some PHP code snippets that will help a few people here and there.
preg_replace_callback()
preg_replace_callback() is a brilliant function to use when handling data straight out of a database, and fromatting it. You can, for example, get a $row = mysql_fetch_array($result), and then pass that array straight to a function like this to format it. This way, you have to change less should you want to manipulate a page in the future.
This function replaces {'value'} in a string with a given $array['value'].
function cool_replace($text, $row) {
return preg_replace_callback('#{([0-9A-Za-z]+)}#',
create_function('$array', 'global $row; return $row[$array[1]];'),
$text);
}
And the function works like so:
$row = array('first' => 'Richard', 'second' => 'Tony', 'third' => 'Nick', 'fourth' => 'Chris');
$text = 'The winner is {first}. Congratulations to {second}, who did very well. {third} and {fourth} came third and fourth respectively. Special attention should be bought to the person in fourth place, which is {fourth}. They got no medal. The Gold medal given to {first} is actually just painted yellow.'
echo cool_replace($text, $row);