Page 1 of 1
Large set string replacement.
Posted: Wed Sep 10, 2003 10:55 pm
by Saint
Ok, I was really wondering what everyone thought would be the best way to do this. String $string has certain character sets I would like to replace with HTML color codes. I have quite a few character sets, and each one has a seperate color code. How would this be done best? Would strtr with 2 arrays be the best? Then I would have to populate the arrays by hand though

. Would storing the pairs in a MySQL database be too innefficant? Any other ways I could do this? Thanks.
Posted: Wed Sep 10, 2003 11:27 pm
by dward
Using strtr() would be the most efficient.
You would probably want to make the array static, so PHP doesn't re-generate the array each time your filter function is called.
Code: Select all
<?php
// Here's an example
// Pass by reference to avoid the pass by copy overhead
function outputFilter(&$sData)
{
static $aFilter = array
(
'red' => '#FF0000',
'white' => '#FFFFFF',
'blue' => '#0033FF'
);
$sData = strtr($sData, $aFilter);
}
// In the main of the program
// Get the data to run the filter over
$sData = get_data_from_somewhere();
// run the filter over the data, since the parameter
// is pass by reference, the newly processed data
// is written in $sData
outputFilter($sData);
// print the data to the client
echo $sData;
?>
Posted: Thu Sep 11, 2003 2:14 am
by JAM
Good example. Worth looking into is also
str_replace() as in:
Code: Select all
// what you dont want...
$from = array("black", "white");
// ...but instead...
$to = array("#000000", "#ffffff");
// replace $string, using those two.
$string = str_replace($from, $to, $string);
Posted: Thu Sep 11, 2003 9:51 pm
by Saint
Well if that's the best way then I guess that's what I'll have to do. Thanks for the example dward. JAM: If I used str_replace, then I'd have to populate 2 arrays, and as they are quite large this wouldn't be very efficent, and it would a pain making sure the source and replacement are in the same place in the two arrays.
Posted: Thu Sep 11, 2003 10:11 pm
by JAM
Very true, it was merely an example of usage. I use str_replace, but I populate both arrays using a database and a language file in that particular project.