1

在我的字符串(实际上是单个页面的 HTML)中,我有许多要访问并替换为相关内容的标签。

例如:

<p>[@intro_text]</p>

会变成:

<p>introduction text!</p>

使用str_replace这一切都很简单,但我也有一系列标签,如下所示:

[@snippet_searchbox]
[@snippet_contactbox]

我需要在 html中找到所有这些标签[@snippet_?????]的出现。

我基本上只想得到一个包含所有标签名称的数组。从这里我可以很容易地找到它应该被替换的内容。

例如:

Array
(
    [0] => snippet_searchbox
    [1] => snippet_contactbox
    [2] => snippet_somethingelse
)

做这个的最好方式是什么?我一直在玩preg_match,但每当我尝试正则表达式时,我都会眼花缭乱,尽管我确信这很简单。

任何建议将不胜感激,如果有人可以帮助我使用我应该使用的正则表达式代码,是否应该使用正则表达式来完成。谢谢!

4

3 回答 3

1

不要为这些标识符发明自己的语法,而是使用常规 (X)HTML 属性:

<html>
    …
    <p id="intro_text"></p>
    …    
    <div id="searchbox"></div>
    …
    <div id="contactbox"></div>
    …
</html>

或命名空间元素:

<html>
    …
    <p tpl:id="intro_text"></p>
    …    
    <tpl:snippet id="searchbox"/>
    …
    <tpl:snippet id="contactbox"/>
    …
</html>

然后使用DOMXPath来查找和替换/修改它们。StackOverflow 上有很多关于如何执行此操作的示例。

于 2012-06-15T12:09:31.533 回答
1

为什么不简单地使用 str_replace ?

str_replace("[@intro_text]", $new_content_of_intro_text, $html_file);
于 2012-06-15T12:13:21.230 回答
1

您可以使用str_replace()

$tags = array(
 '[@intro_text]'        => 'introduction text!',
 '[@snippet_searchbox]' => '<div>some text</div>',
 /* more items here */
);

$html = str_replace(array_keys($tags), array_values($tags), $html);
于 2012-06-15T12:11:13.387 回答