Search code examples
phpstringoffsetnotice

PHP Notice: Uninitialized string offset: -1


i get this error on line 14, this code i use to get a part of url (example: enterforce.nnnet/server2/server3/ for server2 example). It's working, but i got this error:

PHP Notice:  Uninitialized string offset: -1

Full code:

<?php

class simpleUrl{
    var $site_path;
    function __construct($site_path){
        $this->site_path = $this->removeSlash($site_path);
    }

    function __toString(){
        return $this->site_path;
    }

    private function removeSlash($string){
        if($string[strlen($string) - 1] == '/')
            $string = '/';
        return $string;
    }
    function segment($segment){
        $url = str_replace($this->site_path, '', $_SERVER['REQUEST_URI']);
        $url = explode('/', $url);
        if( isset($url[$segment]) )
            return $url[$segment];
        else
            return false;
    }
}

?>

And line 14:

if($string[strlen($string) - 1] == '/')

Solution

  • The reason of the problem is that the $string variable is empty. It seems, you just need to strip the trailing slash. Try this:

    private function removeSlash($string){
        return rtrim($string, '/');
    }
    

    See http://php.net/manual/en/function.rtrim.php