Q:

Regular Expression: Changes HTML Attributes Value to some pattern

I have thousands html tags, have wrote like this: 
<input type="text" name="CustomerName" /> 
<input type="text" name="SalesOrder"/>
I need to match every name attribute values and convert them all to be like this:
CustomerName -> cust[customer_name]
SalesOrder -> cust[sales_order]
So the results will be :
<input type="text" name="cust[customer_name]" /> 
<input type="text" name="cust[sales_order]" />
My best try have stuck in this pattern:
name=\"[a-zA-Z0-9]*\" -> just found name="CustomerName" 
Thanks in advance.

A:

Something like this?
<?php
$subject = <<<EOT
<input type="text" name="CustomerName" />
<input type="text" name="SalesOrder"/>
EOT;
$pattern = '/\\bname=["\']([A-Za-z0-9]+)["\']/';
$output = preg_replace_callback($pattern, function ($match) {
    return ''
    . 'name="cust['
    . strtolower(preg_replace('/(?<=[a-z])([A-Z])/', '_$1', $match[1]))
    . ']"';
}, $subject);
?>
<pre><?php echo htmlentities($output);?></pre>

Output looks like this:
<input type="text" name="cust[customer_name]" />
<input type="text" name="cust[sales_order]"/>

