已弃用的 strlen():将 null 传递给字符串类型的参数 #1 ($string) 已弃用

Depreciated strlen(): Passing null to parameter #1 ($string) of type string is depreciated

提问人:Andy 提问时间:1/9/2023 最后编辑:Andy 更新时间:1/9/2023 访问量:4945

问:

your text

从 PHP 7.4 升级后,在 PHP 8.1 中显示上述警告

关于如何更改此代码以实现 PHP 8.1 兼容性的任何想法?

   private function cleanInput2($strRawText, $strAllowableChars, $blnAllowAccentedChars)
    {
        $iCharPos = 0;
        $chrThisChar = "";
        $strCleanedText = "";

        //Compare each character based on list of acceptable characters
        while ($iCharPos < strlen($strRawText))
        {
            // Only include valid characters **
            $chrThisChar = substr($strRawText, $iCharPos, 1);
            if (strpos($strAllowableChars, $chrThisChar) !== FALSE)
            {
                $strCleanedText = $strCleanedText . $chrThisChar;
            }
            elseIf ($blnAllowAccentedChars == TRUE)
            {
                // Allow accented characters and most high order bit chars which are harmless **
                if (ord($chrThisChar) >= 191)
                {
                    $strCleanedText = $strCleanedText . $chrThisChar;
                }
            }

            $iCharPos = $iCharPos + 1;
        }

        return $strCleanedText;
    }
   
php 字符串 类型 null strlen

评论


答:

3赞 Ammar 1/9/2023 #1

在传递给 strlen() 之前,您应该检查 your 以确保它不是 null。这可以通过显式检查或添加 typehint 来完成。$strRawText

您也可以使用空合并;哪个更简洁。

while ($iCharPos < strlen($strRawText ?? '')) ...

评论

0赞 risingballs 6/12/2023
虽然也可以做 while ($pos < (is_null( $text ) ? 0 : strlen( $text ))) ...我宁愿将整个代码块包装成一个 if (!is_null( $text )) ...通常避免不必要的调用和代码执行。为了可读性,Null 合并也是可能的,但它涉及不必要的调用,具体取决于情况的复杂性。