Question

Using PHP I am running str_replace many times in a row to switch one thing out with another like this:

$a = str_replace("cake", "c_", $a);
$a = str_replace("backup", "bk_", $a);
$a = str_replace("tax_documents", "tax_", $a);

And so on for thirty lines. What is the most efficient way of doing this?

Was it helpful?

Solution

You can write the replacement rules like so:

$replacements = array(
             'cake' => 'c_',
           'backup' => 'bk_',
    'tax_documents' => 'tax_'
);

Then use str_replace like this:

$toReplace = array_keys($replacements);
$replaceWith = array_values($replacements);
$a = str_replace($toReplace, $replaceWith, $a);

OTHER TIPS

The str_replace function will take arrays for the search and replace arguments. Try this.

$finds = array("cake", "backup", "tax_documents");
$reps  = array("c_", "bk_", "tax_");
$a = str_replace($finds, $reps, $a);

Use arrays!

$a = str_replace(array("cake", "backup", "tax_documents"), array("c_", "bk_", "tax_"), $a);

preg_replace().

Try:

$a = str_replace(array("tax_documents", "backup", "cake"), array("tax_", "bk_", "c_"), $a);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top