2

I want to use the php function preg_match_all to find a part of the html code to replace it by another one.

This is what I need to find:

<attachfiles>
tag{link} attr{rel="stylesheet" type="text/css" media="screen"} 
sources{
file1.css,
file2.css
}
</attachfiles>

I made a regular expression that find it but only if that code is present once into the entire html.

My regular expression is:

"|\<attachfiles\>(.*)\<\/attachfiles\>|s"

The issue comes out when I have the code to find repeated two or more times. Since the regular expression uses the |s operator (multiline), when I have the code more than one time it returns all the html code from the very first to the vary last

For example:

<attachfiles>
tag{link} attr{rel="stylesheet" type="text/css" media="screen"} 
sources{
file1.css,
file2.css
}
</attachfiles>

... html code ...
... html code ...

<attachfiles>
tag{script} attr{type="text/css" language="javascript"} 
sources{
file1.js,
file2.js
}
</attachfiles>

My regular expression in this case is returning ALL the code, from the first

<attachfiles> to the last </attachfiles> 

including the

... html code ... 
... html code ... 

that is between the code that I am searching for.

hakre
  • 193,403
  • 52
  • 435
  • 836
Ivano
  • 72
  • 6
  • 2
    See http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – Bill Karwin Sep 18 '10 at 23:05

1 Answers1

0

Use the DOM and create a new DOMDocument() then loadHTML($html) and do getElementsByTagName('attachfiles') then iterate through the ->length with ->item(i), then do what you want.. replaceChild or whatever.

meder omuraliev
  • 183,342
  • 71
  • 393
  • 434
  • Thanks Topera for the link and Meder for your solution!. – Ivano Sep 19 '10 at 00:46
  • I ve been reading the regular expression modificators and I solved the issue using a couple of them. Using "|\(.*)\<\/attachfiles\>|msU" worke perfect!. Thanks again!! – Ivano Sep 19 '10 at 00:48