PHP注意:未初始化的字符串偏移0

时间:2015-07-29 12:22:16

标签: php

自升级到PHP 5.4以来,我出现了恼人的PHP通知错误。我可以看到它发生的地方,但我没有专业知识来纠正代码并停止通知。

PHP注意:未初始化的字符串偏移量:0

它发生在代码的第108行,实际上是指这一行: $contents[$o] = $this->unicode_entity_replace($contents[$o]);

有问题的功能如下:

class unicode_replace_entities {
        public function UTF8entities($content="") {
            $contents = $this->unicode_string_to_array($content);
            $swap = "";
            $iCount = count($contents);
            for ($o=0;$o<$iCount;$o++) {
                $contents[$o] = $this->unicode_entity_replace($contents[$o]);
               $swap .= $contents[$o];
            }
            return mb_convert_encoding($swap,"UTF-8");
        }

非常感谢任何帮助或解释。

编辑:以下课程剩余课程的完整代码(道歉之前未包含):

            public function unicode_string_to_array( $string ) { //adjwilli
            $strlen = mb_strlen($string);
            $array = "";
            while ($strlen) {
                $array[] = mb_substr( $string, 0, 1, "UTF-8" );
                $string = mb_substr( $string, 1, $strlen, "UTF-8" );
                $strlen = mb_strlen( $string );
            }
            return $array;
        }

        public function unicode_entity_replace($c) { //m. perez
            $h = ord($c{0});   
            if ($h <= 0x7F) {
                return $c;
            } else if ($h < 0xC2) {
                return $c;
            }

            if ($h <= 0xDF) {
                $h = ($h & 0x1F) << 6 | (ord($c{1}) & 0x3F);
                $h = "&#" . $h . ";";
                return $h;
            } else if ($h <= 0xEF) {
                $h = ($h & 0x0F) << 12 | (ord($c{1}) & 0x3F) << 6 | (ord($c{2}) & 0x3F);
                $h = "&#" . $h . ";";
                return $h;
            } else if ($h <= 0xF4) {
                $h = ($h & 0x0F) << 18 | (ord($c{1}) & 0x3F) << 12 | (ord($c{2}) & 0x3F) << 6 | (ord($c{3}) & 0x3F);
                $h = "&#" . $h . ";";
               return $h;
            }
        }

3 个答案:

答案 0 :(得分:1)

如果对$s[1]这样的字符串使用数组语法,它将访问第二个字母。但是,如果字符串为空,则会出现偏移错误。您可以使用!empty($s)阻止此操作,或确保您确实使用的数组为is_array()

答案 1 :(得分:0)

foreach怎么样?

.has_children

答案 2 :(得分:0)

我设法解决了这个问题。正如另一个有用的灵魂指出的那样,unicode_string_to_array函数中的$array = "";导致$ array成为字符串,而不是数组。它应该使用$array = array();

进行初始化