Skip to content

CascadeStringReplacement ​

warning on by default quick-fix

Group: Performance · PhpStorm name: CascadeStringReplacementInspection

str_replace() accepts arrays of searches and replacements and applies them in order, so several consecutive replacements on the same subject — written as back-to-back assignments or as nested calls — can be one call. Also, a search array whose items are all the same string literal can be that string.

Example ​

Short array syntax option on.

php
<?php
function slug($title, $raw, $line) {
    $title = str_replace('&', 'and', $title);
    /** spaces */
    $title = str_replace(' ', '-', $title);
    return str_replace(['.', ','], '', $title);
}

function others($raw, $line) {
    $code = str_replace('_', '-', str_replace(' ', '_', $raw));
    $mark = str_replace(['k'], ['!'], str_replace('j', '!', $raw));
    $clean = str_replace(array("\t", "\t"), ' ', $line);

    $x = str_replace('a', 'b', $raw);
    $y = str_replace('c', 'd', $x);
    $keep = str_replace(['a', 'b'], 'c', $line);
    log_it(str_replace('q', 'r', str_replace('s', 't', $line)));
    return $y;
}
php
<?php
function slug($title, $raw, $line) {
    /** spaces */
    return str_replace(['&', ' ', '.', ','], ['and', '-', '', ''], $title);
}

function others($raw, $line) {
    $code = str_replace([' ', '_'], ['_', '-'], $raw);
    $mark = str_replace(['j', 'k'], '!', $raw);
    $clean = str_replace("\t", ' ', $line);

    $x = str_replace('a', 'b', $raw);
    $y = str_replace('c', 'd', $x);
    $keep = str_replace(['a', 'b'], 'c', $line);
    log_it(str_replace('q', 'r', str_replace('s', 't', $line)));
    return $y;
}

Reported:

  • line 5: Fold this str_replace() into the preceding one on the same variable.
  • line 6: Fold this str_replace() into the preceding one on the same variable.
  • line 10: Fold this nested str_replace() into the enclosing call.
  • line 11: Fold this nested str_replace() into the enclosing call.
  • line 12: All searched items are identical; pass the single string.

Options ​

OptionTypeDefaultEffect
USE_SHORT_ARRAYS_SYNTAXboolfalseArray syntax for arrays in the rebuilt call (F5): [...] when true, array(...) when false. Detection unaffected. Upstream fixtures run with true.

Configure ​

In custos.json:

json
{
  "rules": {
    "CascadeStringReplacement": {
      "enabled": false,
      "options": {
        "USE_SHORT_ARRAYS_SYNTAX": false
      }
    }
  }
}

Suppress ​

Before the statement or declaration (or the first statement of the file), either of:

php
// @custos-ignore CascadeStringReplacement

/**
 * @noinspection CascadeStringReplacementInspection
 */

Released under the MIT License. Rule catalogue modelled on Php Inspections (EA Extended); independent clean-room implementation.