2

我想使用 php 函数 preg_match_all 来查找 html 代码的一部分以将其替换为另一个。

这是我需要找到的:

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

我做了一个正则表达式来找到它,但前提是该代码在整个 html 中出现一次。

我的正则表达式是:

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

当我找到重复两次或更多次的代码时,问题就出现了。由于正则表达式使用 |s 运算符(多行),因此当我多次使用代码时,它会返回从第一个到最后变化的所有 html 代码

例如:

<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>

在这种情况下,我的正则表达式从第一个返回所有代码

<attachfiles> to the last </attachfiles> 

包括

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

那是我正在搜索的代码之间。

4

1 回答 1

0

使用 DOM 并创建一个new DOMDocument()then然后遍历with ,然后loadHTML($html)做你想做的事..或其他任何事情。getElementsByTagName('attachfiles')->length->item(i)replaceChild

于 2010-09-18T22:49:43.920 回答