Large set string 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

Post Reply
Saint
Forum Newbie
Posts: 4
Joined: Wed Sep 10, 2003 10:55 pm
Location: CO, USA
Contact:

Large set string replacement.

Post 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.
dward
Forum Newbie
Posts: 1
Joined: Wed Sep 10, 2003 11:27 pm
Location: Moline, IL, USA

Post 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;

?>
User avatar
JAM
DevNet Resident
Posts: 2101
Joined: Fri Aug 08, 2003 6:53 pm
Location: Sweden
Contact:

Post 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);
Saint
Forum Newbie
Posts: 4
Joined: Wed Sep 10, 2003 10:55 pm
Location: CO, USA
Contact:

Post 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.
User avatar
JAM
DevNet Resident
Posts: 2101
Joined: Fri Aug 08, 2003 6:53 pm
Location: Sweden
Contact:

Post 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.
Post Reply