1

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.

2 Answers 2

2

Parsing HTML is not a good use of RegEx. Please see here.

With that said, this might be a small enough task that it won't drive you insane. You'd need something like:

Find: name="(.+)"

Replace: name="cust[$1]"

and then hope that your HTML isn't very irregular (most is, but you can always hope).

Update: here's some sed-fu to get you started on camelCase -> underscores.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your fast response i'm playing around the camelCase now
0

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]"/>

2 Comments

Dear kristof, what a smart technique. You was done this like magics ! Thank you very much.
Hello Brain, could you be so kind as to click on the big V next to my answer? That way I get points. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.