SubStrShortHandUsage
warning on by default quick-fixGroup: Performance · PhpStorm name: SubStrShortHandUsageInspection
substr() / mb_substr() accept a negative length ("stop N characters before the end") and treat a missing length as "up to the end". Computing the length as strlen($s) - something is therefore either replaceable by a negative constant, or entirely unnecessary.
Example
php
<?php
function cut($name, $head, $k) {
$a = substr($name, 0, strlen($name) - 4);
$b = mb_substr($name, 3, mb_strlen($name) - 5, 'UTF-8');
$c = \substr($name, 7, strlen($name) - 2);
$d = mb_substr($name, $k, mb_strlen($name) - $k);
$e = mb_substr(
$name,
strlen($head),
mb_strlen($name) - strlen($head),
'UTF-8'
);
$f = substr($name, $k, strlen($name) - 1);
$g = substr($name, 0, strlen($head) - 1);
$h = substr($name, 0, (strlen($name) - 1));
$i = substr($name, 0x1, strlen($name) - 2);
$j = substr($name, 0, mb_strlen($name, 'UTF-8') - 1);
$m = mb_substr($name, 0, strlen($name) - 2);
return [$a, $b, $c, $d, $e, $f, $g, $h, $i, $j, $m];
}php
<?php
function cut($name, $head, $k) {
$a = substr($name, 0, -4);
$b = mb_substr($name, 3, -2, 'UTF-8');
$c = \substr($name, 7);
$d = mb_substr($name, $k);
$e = mb_substr(
$name, strlen($head), null, 'UTF-8'
);
$f = substr($name, $k, strlen($name) - 1);
$g = substr($name, 0, strlen($head) - 1);
$h = substr($name, 0, (strlen($name) - 1));
$i = substr($name, 0x1, strlen($name) - 2);
$j = substr($name, 0, mb_strlen($name, 'UTF-8') - 1);
$m = mb_substr($name, 0, strlen($name) - 2);
return [$a, $b, $c, $d, $e, $f, $g, $h, $i, $j, $m];
}Reported:
- line 3: Pass '-4' as the length instead.
- line 4: Pass '-2' as the length instead.
- line 5: The length 'strlen($name) - 2' is unnecessary; remove it.
- line 6: The length 'mb_strlen($name) - $k' is unnecessary; remove it.
- line 10: The length 'mb_strlen($name) - strlen($head)' is unnecessary; remove it.
Configure
In custos.json:
json
{
"rules": {
"SubStrShortHandUsage": {
"enabled": false
}
}
}Suppress
Before the statement or declaration (or the first statement of the file), either of:
php
// @custos-ignore SubStrShortHandUsage
/**
* @noinspection SubStrShortHandUsageInspection
*/