1.2.1177. Substr To Trim¶
When removing the first or the last character of a string, trim() does a more readable job.
trim(), ltrim() and rtrim() accept a string as second argument. Those will all be removed from the endings of the string. trim() will remove all occurrences of the requested char(). This may remove a loop with substr(), or remove more than is needed.
trim() doesn’t work with multi-bytes strings, but so does substr(). For that, use mb_substr(), as there isn’t any mb_trim() function (so far in PHP 8.2).
<?php
$a = '$drop the dollar';
$b = substr($a, 1); // drop the first char
$b = ltrim($a, '$'); // remove the initial '$'s
$b = substr($a, 1); // replace with ltrim()
$b = substr($a, 0, -1); // replace with rtrim()
$b = substr($a, 1, -1); // replace with trim()
?>
See also trim, ltrim and rtrim.
1.2.1177.1. Suggestions¶
Replace substr() with trim(), ltrim() or rtrim().
1.2.1177.2. Specs¶
Short name |
Structures/SubstrToTrim |
Rulesets |
|
Exakat since |
1.8.3 |
PHP Version |
All |
Severity |
Minor |
Time To Fix |
Quick (30 mins) |
Precision |
High |
Available in |