2013-03-28 83 views
4

在PHP以下是有效的:字符串作爲數組

$n='abc'; 
echo $n[1]; 

但似乎以下'abc'[1];不是。

解析器有什麼問題嗎?

不幸的是,目前即使$n[1]語法也不是很有用◕(◕,因爲它不支持Unicode並返回字節而不是字母。

回答

10

echo 'abc'[1];只適用於PHP 5.5see Full RFC$n[1] or $n{2}是在PHP

See Live Test

所有版本valid遺憾的是目前甚至$n[1]語法也不是那麼有用◕(◕,因爲它不支持Unicode並返回字節而不是字母。

爲什麼不只是創建你自己?例如:

$str = "Büyük"; 
echo $str[1], PHP_EOL; 

$s = new StringArray($str); 
echo $s[1], PHP_EOL; 

// or 

echo new StringArray($str, 1, 1), PHP_EOL; 

輸出

� 
ü 
ü 

類使用,

class StringArray implements ArrayAccess { 
    private $slice = array(); 

    public function __construct($str, $start = null, $length = null) { 
     $this->slice = preg_split("//u", $str, - 1, PREG_SPLIT_NO_EMPTY); 
     $this->slice = array_slice($this->slice, (int) $start, (int) $length ? : count($this->slice)); 
    } 

    public function slice($start = null, $length = null) { 
     $this->slice = array_slice($this->string, (int) $start, (int) $length); 
     return $this ; 
    } 

    public function offsetSet($offset, $value) { 
     if (is_null($offset)) { 
      $this->slice[] = $value; 
     } else { 
      $this->slice[$offset] = $value; 
     } 
    } 

    public function offsetExists($offset) { 
     return isset($this->slice[$offset]); 
    } 

    public function offsetUnset($offset) { 
     unset($this->slice[$offset]); 
    } 

    public function offsetGet($offset) { 
     return isset($this->slice[$offset]) ? $this->slice[$offset] : null; 
    } 

    function __toString() { 
     return implode($this->slice); 
    } 
} 
+2

它也在文檔中明確聲明:http://php.net/manual/en/language.types.string.php –

1

不,這是正常的操作。做你正在嘗試,你可以嘗試:

echo substr('abc', 1, 1); 
0

文本字符串訪問語法'abc'[1]在JavaScript中非常有效,但不會在PHP的支持,直到版本5.5