Skip to content

StringsFirstCharactersCompare ​

error on by default quick-fix

Group: Probable bugs · PhpStorm name: StringsFirstCharactersCompareInspection

strncmp()/strncasecmp() with a literal prefix and a hard-coded length that does not match the literal's length compares too few (or too many) characters — usually a leftover after editing the literal.

Example ​

php
<?php
function route(string $uri) {
    if (strncmp($uri, '/api/', 4) === 0) {}
    if (strncmp('/admin', $uri, 9) === 0) {}
    if (\strncasecmp($uri, "HTTP\t", 6) === 0) {}
    if (strncasecmp($uri, 'C:\\x', -1) === 0) {}
    if (strncmp($uri, '/static/', 8) === 0) {}
    if (strncmp($uri, 'back\\slash', 10) === 0) {}
    if (strncmp($uri, '', 3) === 0) {}
    if (strncmp($uri, '/x', 0x2) === 0) {}
    if (strncmp($uri, '/v1/', strlen('/v1/')) === 0) {}
    if (strncmp($uri, $prefix, 4) === 0) {}
}
php
<?php
function route(string $uri) {
    if (strncmp($uri, '/api/', 5) === 0) {}
    if (strncmp('/admin', $uri, 6) === 0) {}
    if (\strncasecmp($uri, "HTTP\t", 5) === 0) {}
    if (strncasecmp($uri, 'C:\\x', 4) === 0) {}
    if (strncmp($uri, '/static/', 8) === 0) {}
    if (strncmp($uri, 'back\\slash', 10) === 0) {}
    if (strncmp($uri, '', 3) === 0) {}
    if (strncmp($uri, '/x', 0x2) === 0) {}
    if (strncmp($uri, '/v1/', strlen('/v1/')) === 0) {}
    if (strncmp($uri, $prefix, 4) === 0) {}
}

Reported:

  • line 3: Length 4 does not match the 5-character literal.
  • line 4: Length 9 does not match the 6-character literal.
  • line 5: Length 6 does not match the 5-character literal.
  • line 6: Length -1 does not match the 4-character literal.

Configure ​

In custos.json:

json
{
  "rules": {
    "StringsFirstCharactersCompare": {
      "enabled": false
    }
  }
}

Suppress ​

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

php
// @custos-ignore StringsFirstCharactersCompare

/**
 * @noinspection StringsFirstCharactersCompareInspection
 */

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