The quick fix in most cases is to use the null coalescing operator to provide a default value as appropriate, so you don't need a long null check around every use. For instance, htmlspecialchars($something) can be replaced with htmlspecialchars($something ?? '')
Rector has the rule NullToStrictStringFuncCallArgRector to fix this:
- mb_strtolower($value);
+ mb_strtolower((string) $value);
I like that better than $value ?? '' –
Depends. One should be aware with the string cast that it turns arrays into the string "Array" while giving a warning (notice before PHP

ref. So you have to consider the appropriate handling beforehand (or at least should when applying automated changes to the overall code-base), to not run into the next maintenance problem. Rector likely does it this way because this is what would happened before, so it preserves the original behaviour. –
hakre
A big difference is that if you are running with strict_mode=1, then htmlspecialchars(42) is already an error; htmlspecialchars(42 ?? '') retains that error, htmlspecialchars((string)42) suppresses it. Similarly, (string)$object will call $object->__toString(), $object ?? '' will not. On the other hand, htmlspecialchars($mistypedVar ?? '') suppresses a Warning which htmlspecialchars((string)$mistypedVar) does not, so neither is a perfect replacement. –
IMSoP
My strong educated guess in context of the question is that htmlspecialchars() and trim() is a signal that not strict types but "string" types is what OP is aiming for, most likely code related to output (template etc.). This is not what strict_mode is of a particular benefit of, so would only add another error as false positive (even a real one, not a deprecation warning). The reason why the internal functions were typed was a different one than the strict_mode IIRC, and I have some sympathy for the cause here, but fear it's not only null but also the 42. –
this is a great way to hide genuine TypeErrors in the code... use ??'' instead. –
I'd like (as an addition, existing answers have my upvotes) to paint a different picture on how to see and tackle with such "problems". It does not make the outlined approaches less right or wrong and is merely an additional view which hopefully is of mutual benefit. And every project is different.
Cheat-Sheet
(string)$mixed - previous behaviour
$mixed ?? '' - error suppression for TypeError on null only
@ - full error suppression. you should document in/for your code-base where it is applicable to use.
@@ - if this comes up, it is likely an interesting spot to look into.
empty($mixed) ? '' : xxx($mixed) - carry the trash out, typical empty paralysis / mixed confusion, look for clusters, there is a chance the code-base can be greatly simplified. migrate to scalar types (PHP 7), pull in strict type handling from most-inner in outwards direction, use both PHP "classic" and "strict" type handling where applicable. PHP 7.0 assertions and PHP 8.1 deprecation messages can support here well.