How to check if is a valid PHP Array in JavaScript / TypeScript?

one text

Is there a way to check if a PHP Array is valid in JavaScript/TypeScript?

Context: my users can add some PHP code to a code textarea which gets saved to a database to later be rendered to some files.

I search for a way to analyze the entered code and to check if the array is valid in the PHP language and has no syntax errors or something else. An array could look like that:

[
  'key'     => 'value',
  '_key'         => [
    '_other_key' => 'value',
  ]
]

Sure. I could check if the string starts with [ and ends with ], but what if the user adds some comments before? It also would be valid in PHP, but would not match the condition.

How would you handle such conditions?

Edit

It's not perfect, but I created some regex replacements to remove all possible comments and ask if the string starts and ends with typical array syntax. Thats better than nothing :-)

syntaxCheck() {
  let code = this.userCode;
  code = code + "\n"; // Added to match the regex for the last line
  code = code.replace(/\/\*.*?\*\/|\/\/.*?\n/mgs, '');
  code = code.replace(/(\r\n|\n|\r)/gm, '');

  let isArray = code.startsWith("array") && code.slice(-1) == ")";
  let isAlternateArray = code.charAt(0) == "[" && code.slice(-1) == "]";
  let hasSemicolonAtEnd = code.slice(-1) == ";"; // Not needed in this case

  if (!isArray && !isAlternateArray || hasSemicolonAtEnd) {
    this.syntaxWarning = true;
  } else {
    this.syntaxWarning = false;
  }
}

If you know a better solution or improvements, I would be thankful :)

Source