How can regex functions like preg_replace be utilized to manipulate serialized PHP arrays for JavaScript object literals?

To manipulate serialized PHP arrays for JavaScript object literals, we can use regex functions like preg_replace to convert the serialized data into a format that can be easily parsed in JavaScript. This involves replacing the PHP array syntax with JavaScript object literal syntax. By using regex functions, we can efficiently perform this transformation on the serialized data.

<?php
$serializedArray = 'a:2:{s:4:"name";s:5:"Alice";s:3:"age";i:30;}';

// Convert serialized PHP array to JavaScript object literal
$jsObject = preg_replace('/s:(\d+):"(.*?)";/s', '"$2":', $serializedArray);
$jsObject = preg_replace('/s:(\d+):"(.*?)";/s', '"$2":', $jsObject);
$jsObject = preg_replace('/i:(\d+);/', '$1,', $jsObject);
$jsObject = str_replace('a:2:{', '{', $jsObject);
$jsObject = str_replace('}', '}', $jsObject);

echo $jsObject;
?>