是否可以使用regexp将"xyz"转换为"x [y] [z]"?

PHP*_*Pst 0 php regex pcre

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

这是我当前的代码,但我想应该有一个使用regexp的更短的方法.

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

  return $input . ']';

}
Run Code Online (Sandbox Code Playgroud)

Rom*_*est 5

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

$input = "x.d.dsaf.d2.d";
print_r(preg_replace("/\.([^.]+)/", "[$1]", $input));  // "x[d][dsaf][d2][d]"
Run Code Online (Sandbox Code Playgroud)