是否可以使用正则表达式将 "x.y.z" 转换为 "x[y][z]"?

Is it possible to convert "x.y.z" to "x[y][z]" using regexp?

将点分隔字符串中的 dots 替换为类似数组的字符串的最有效模式是什么,例如 x.y.z -> x[y][z]

这是我当前的代码,但我想应该有一个使用正则表达式的更短的方法。

function convert($input)
{
  if (strpos($input, '.') === false) {
    return $input;
  }
  $input = str_replace_first('.', '[', $input);
  $input = str_replace('.', '][', $input);

  return $input . ']';

}

在您的特定情况下,可以使用 preg_replace 函数轻松获得“类数组字符串”:

$input = "x.d.dsaf.d2.d";
print_r(preg_replace("/\.([^.]+)/", "[]", $input));  // "x[d][dsaf][d2][d]"

从你的问题中我了解到; "x.y.z" 是一个字符串,所以 "x[y][z]" 应该是,对吧? 如果是这种情况,您可能想尝试以下代码片段:

        <?php           
            $dotSeparatedString = "x.y.z";
            $arrayLikeString    = "";
            //HERE IS THE REGEX YOU ASKED FOR...
            $arrayLikeString    = str_replace(".", "", preg_replace("#(\.[a-z0-9]*[^.])#", "[]", $dotSeparatedString));

            var_dump($arrayLikeString);     //DUMPS: 'x[y][z]' 

不过希望对你有所帮助....

使用一个相当简单的 preg_replace_callback() 简单地 returns 与其他出现的 . 的第一次出现不同的替换。

$in = "x.y.z";

function cb($matches) {
    static $first = true;
    if (!$first) 
        return '][';
    $first = false;
    return '[';
}

$out = preg_replace_callback('/(\.)/', 'cb', $in) . ((strpos('.', $in) !== false) ? ']' : ']');
var_dump($out);

三元追加是为了处理没有.的情况来替换

已回答,但您可以简单地在句点分隔符上展开,然后重建一个字符串。

$in = 'x.y.z';

$array = explode('.', $in);

$out = '';

foreach ($array as $key => $part){
    $out .= ($key) ? '[' . $part . ']' : $part;
}

echo $out;