-
[RESOLVED] help with RegExp
Hi,
could you help me to find the right RegExp to solve my problem? In htmlText are images and I need to assign them unique ID
original:
Code:
<img src="/imgs/image001.jpg" width="150" height="100" /> text text text text text text text text
<img src="/imgs/image002.jpg" width="180" height="100" /> text text text text text text text text
<img src="/imgs/image006.jpg" width="170" height="100" /> text text text text text text text text
<img src="/imgs/image005.jpg" width="160" height="100" /> text text text text text text text text
<img src="/imgs/image022.jpg" width="140" height="100" id="myid"/> text text text text text text text text
<img src="/imgs/image109.jpg" width="110" height="100" /> text text text text text text text text
converted:
Code:
<img src="/imgs/image001.jpg" width="150" height="100" id="pic1"/> text text text text text text text text
<img src="/imgs/image002.jpg" width="180" height="100" id="pic2"/> text text text text text text text text
<img src="/imgs/image006.jpg" width="170" height="100" id="pic3"/> text text text text text text text text
<img src="/imgs/image005.jpg" width="160" height="100" id="pic4"/> text text text text text text text text
<img src="/imgs/image022.jpg" width="140" height="100" id="pic5"/> text text text text text text text text
<img src="/imgs/image109.jpg" width="110" height="100" id="pic6"/> text text text text text text text text
Thanks!
-
you can't do it with just regexp - you need a little logic.
also, i see one line in the original already has an id - not sure if that's supposed to be there or not - i presumed it might, so accounted for it.
this works, but is a little hacky:
PHP Code:
var n:int = 1; var converted:String = original.replace(/id=\"(\w+)\"/gm, '').replace(/\s+?\/>/gm, function(a,b,c):String{ return " id=\"pic" + (n++) + "\"" + a; });
personally, instead of regexp, i'd turn that into xml, then set the "id" attribute, then output the new XML as a string, like so:
PHP Code:
var xml:XML = new XML('<root>' + original + '</root>'); var l:int = xml.img.length(); for (var i:int=0; i<l; i++) { xml.img[i].@id = "pic" + i; } trace(xml);
if those text nodes weren't floating around, you could do something a little more elegant using childIndex, possibly using straight E4X assignment, but that's probably not likely if you're pulling from text
-
moagrius,
that's nice one! Turning that to XML is a perfect solution!
Thanks a lot!
-
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|