繁体   English   中英

字符串作为数组

[英]Strings as arrays

在PHP中,以下内容有效:

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

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

解析器有什么问题吗?

不幸的是,目前即使$n[1]语法也不太有用because,因为它不支持Unicode并返回字节而不是字母。

echo 'abc'[1]; 仅在PHP 5.5有效, 请参见完整RFC,$n[1] or $n{2}在所有版本的PHP中均有效

查看实时测试

不幸的是,目前即使$n[1]语法也不太有用because,因为它不支持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);
    }
}

不,这是正确的操作。 要执行您想做的事情,可以尝试:

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

文字字符串访问语法'abc'[1]在JavaScript中非常有效,但直到版本5.5才在PHP中受支持。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM