Reputation: 245
Ok, so say I have a bunch of input
s in an HTML file like this:
<input class="form-control" type="text" id="ogwb">
<input class="form-control" type="text" id="aosgh">
<input class="form-control" type="text" id="aghw">
How can I replace all instances of the id
s with themselves and a name
and value
attribute having the same id
value like so:
<input class="form-control" type="text" id="ogwb" name="ogwb" value="<?php echo htmlspecialchars($_POST['ogwb']); ?>">
<input class="form-control" type="text" id="aosgh" name="aosgh" value="<?php echo htmlspecialchars($_POST['aosgh']); ?>">
<input class="form-control" type="text" id="aghw" name="aghw" value="<?php echo htmlspecialchars($_POST['aghw']); ?>">
This is what I've tried:
f = File.read('my.html')
$arr = f.scan(/id="([^"]*)"/)
$arr.each{ |a|
e_ = a.join(", ")+'"'
e__ = a.join(", ")+'"'+' name="'+a.join(", ")+'" value="<?php echo htmlspecialchars($_POST['+"'"+a.join(", ")+"'"+']); ?>"'
f.gsub(/#{e_}/,e__)
}
Which if I do puts e_
and puts e__
I get the match and replace I want, but gsub
doesn't seem to work.
Upvotes: 0
Views: 51
Reputation: 8377
You will want to use regex to grab this:
<input class="form-control" type="text" id="([^"]+)">
Notice that I surrounded the text value of the id with a capturing group (the brackets). This is capture group #1.
You can access the first captured group with \1
.
So you'll want to search for the previous regex, and replace it with the following:
<input class="form-control" type="text" id="\1" name="\1" value="<?php echo htmlspecialchars($_POST['\1']); ?>">
Demonstration: https://regex101.com/r/qeHkmg/1
Documentation: http://www.regular-expressions.info/replacebackref.html
Upvotes: 1