在preg_match_all问题中的preg_replace

时间:2010-01-04 23:00:52

标签: php preg-replace preg-match-all

我正在尝试在我的数据文件中找到某些块并替换它们内部的某些内容。之后将整个事物(替换数据)放入新文件中。我的代码目前看起来像这样:

$content = file_get_contents('file.ext', true);

//find certain pattern blocks first
preg_match_all('/regexp/su', $content, $matches);

foreach ($matches[0] as $match) {
  //replace data inside of those blocks
  preg_replace('/regexp2/su', 'replacement', $match);
}

file_put_contents('new_file.ext', return_whole_thing?);

现在问题是我不知道如何return_whole_thing。基本上,除了替换的数据之外,file.ext和new_file.ext几乎相同。 有什么建议应该代替return_whole_thing吗?

谢谢!

3 个答案:

答案 0 :(得分:2)

你甚至不需要preg_replace;因为你已经有了匹配,你可以使用正常的str_replace,如下所示:

$content = file_get_contents('file.ext', true);

//find certain pattern blocks first
preg_match_all('/regexp/su', $content, $matches);

foreach ($matches[0] as $match) {
  //replace data inside of those blocks
  $content = str_replace( $match, 'replacement', $content)
}

file_put_contents('new_file.ext', $content);

答案 1 :(得分:0)

我不确定我理解你的问题。你可以发一个例子:

  • file.ext,原始文件
  • 您要使用的正则表达式以及要替换的内容与
  • 匹配
  • new_file.ext,您想要的输出

如果您只想阅读file.ext,请替换正则表达式匹配,并将结果存储在new_file.ext中,您的所有需求均为:

$content = file_get_contents('file.ext');
$content = preg_replace('/match/', 'replacement', $content);
file_put_contents('new_file.ext', $content);

答案 2 :(得分:0)

最好加强正则表达式以在原始模式中查找子模式。这样你就可以调用preg_replace()并完成它。

$new_file_contents = preg_replace('/regular(Exp)/', 'replacement', $content);

这可以使用正则表达式中的“()”来完成。快速谷歌搜索“正则表达式子模式”导致this

相关问题