【发布时间】:2010-12-21 10:11:08
【问题描述】:
我没有在 PHP 中使用正则表达式的经验,所以我通常使用一系列 str_replace()、substr()、strpos()、strstr() 等来编写一些复杂的函数(你懂的)。
这次我想正确地执行此操作,我知道我需要为此使用正则表达式,但对使用什么(ereg 或 preg)以及语法应该如何准确感到困惑。
注意:我不是在解析 HTML 或 XML,有时我会使用除 (例如 | 或 ~ 或 [tag] 或 ::) 以外的分隔符。我正在寻找一种通用方法来使用正则表达式在两个已知分隔符之间进行通配符替换,我不是在构建 HTML 或 XML 解析器。
我需要的是一个替换这个的正则表达式:
<sometag>everything in here</sometag>
用这个:
<sometag>new contents</sometag>
我已经在线阅读了一些文档,但我很困惑,我希望你们中的一位正则表达式专家可以提出一个简单的解决方案。我怀疑我会将值传递给函数,如下所示:
$new_text = swapText ( "<sometag>", $the_new_text_to_go_into_the_dag );
function swapText ( $in_tag_with_brackets_to_update, $in_new_text ) {
// define tags
$starting_tag = $in_tag_with_brackets_to_update;
$ending_tag = str_replace( "<", "</", $in_tag_with_brackets_to_update) );
// not sure if this is the proper regex match string or not
// and/or if any escaping needs to be done on the tags
$find_string = "{$starting_tag}.*{$ending_tag}";
$replace_with_string = "{$starting_tag}{$in_new_text}{$ending_tag}";
// after some regex, this function should return new version of <tag>data</tag>
}
谢谢。
【问题讨论】:
-
感谢 BalusC,但我并没有尝试解析 HTML,尽管我可以看到我的问题可能会让您相信这一点。
-
你在做模板引擎吗?
-
Galen - 我只是在寻找一种方法来替换已知分隔符集中的未知文本块(我使用标签作为我将用作分隔符的众多事物之一的示例) .也许我应该为分隔符使用不同的示例。
-
即使您的标签不是真正的 HTML 标签,如果它们始终遵循 HTML/XML 格式,解析器仍然是更好的选择。您应该能够轻松找到/替换
sometag中的所有内容。