【问题标题】:Strings as arrays字符串作为数组
【发布时间】:2013-03-28 19:47:12
【问题描述】:

在 PHP 中以下是有效的:

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

但是下面的'abc'[1];好像不是。

它的解析器有什么问题吗?

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

【问题讨论】:

    标签: php arrays string syntax


    【解决方案1】:

    echo 'abc'[1]; 仅在PHP 5.5 see Full RFC 中有效,但$n[1] or $n{2}PHP 的所有版本中都是valid

    See Live Test

    不幸的是,目前即使 $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】:

    不,这是正确的操作。做你想做的事,你可以尝试:

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-15
        • 2018-12-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-14
        • 1970-01-01
        相关资源
        最近更新 更多