是否可以将子字符串替换为dom元素

时间:2012-02-18 13:53:17

标签: php regex dom str-replace

我有一个情况,我是一个java家伙,并得到一些困难的时间与PHP。 我正在从数据库创建XML文件。现在,我创建了90多个动态元素,其中包括属性,子等,没有任何问题。 但事情搞砸了;

的text1: here is a list of pencils[1]. here is a list of another type of pencils[2].

我确实想要

<text1>

here is a list of pencils <id>1</id>. here is a list of another type of pencils <id>2</id>.

</text1>

我可以替换子串([1],[2])并插入一些其他文本,但如何用DOM元素替换这些子串?

任何帮助都深受赞赏..

1 个答案:

答案 0 :(得分:1)

您不能,因为您想要进行替换的字符串是node Value节点的text1。一个变体就是构造它:

<text1>
  <partial>here is a list of pencils</partial>
  <id>1</id>
  <partial>.here is a list of another type of pencils</partial>
  <id>2</id>
</text1>

但老实说这不是最理想的。

我认为让你感到困惑的是(和我在那里呆了一秒钟)是我们写HTML的方式:

<p>some text here <a href="...">a link</a> more <strong>variation</strong></p>

这可能会让我们觉得它也应该是有效的XML;但当然还有另一件事要知道;浏览器实际上将先前的HTML转换为以下形式(〜):

<p>
  <textnode>some text here </textnode>
  <a href="...">
    <textnode>a link</a>
  </a>
  <textnode> more </textnode>
  <strong>variation</strong>
</p>

不是答案,但我建议您重新考虑XML格式。