开发者

I overused str_replace and can't figure out a better way

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?


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜