Regex For Html Attribute Replacement/addition
I'm looking for a single line regex which does the following: Given a HTML tag with the 'name' attribute, I want to replace it with my own attribute. If that tag lacks the name att
Solution 1:
The trick is to match every complete "attribute=value" pair, but capture only the ones whose attribute name isn't "name". Then plug in your own "name" attribute along with all the captured ones.
s/<IMG
((?:\s+(?!name\b)\w+="[^"]+")*)
(?:\s+name="[^"]+")?
((?:\s+(?!name\b)\w+="[^"]+")*)
>
/<IMG name="myName"$1$2>
/xg;
Solution 2:
This isn't a perfect solution, the spacing and position within the tag may not be exactly what you want, but it does accomplish the goals. This is with a perl regex, but there's nothing particular perl-specific about it.
s/(<IMG)((\s+[^>]*)name="[^"]*")?(.*)/$1$3 name="myID"$4/g
Solution 3:
If, like in your example, the name attribute is always the first one inside the IMG tag, then it's very easy. Search for
<(?!/)(/w+)\s+(name="[^"]+")?
and replace with
<\1 name="myImg1"
but I doubt that this is what you really want.
If the name attribute can occur in other positions, it gets more difficult.
Post a Comment for "Regex For Html Attribute Replacement/addition"