PHPst PHPst - 7 months ago 11
PHP Question

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

What is the most efficient pattern to replace

dots
in dot-separated string to an array-like string e.g
x.y.z -> x[y][z]


Here is my current code, but I guess there should be a shorter method using regexp.

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

return $input . ']';

}

Answer

In your particular case "an array-like string" can be easily obtained using preg_replace function:

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