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
吗?
谢谢你!
I'm trying to find some certain blocks in my data file and replace something inside of them. After that put the whole thing (with replaced data) into a new file. My code at the moment looks like this:
$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?);
Now the problem is I don't know how to return_whole_thing. Basically, file.ext and new_file.ext are almost the same except of the replaced data.
Any suggestion what should be on place of return_whole_thing
?
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你甚至不需要 preg_replace;因为您已经获得了匹配项,所以您可以使用普通的 str_replace ,如下所示:
You don't even need the preg_replace; because you've already got the matches you can just use a normal str_replace like so:
最好加强正则表达式以在原始模式中找到子模式。这样你就可以调用 preg_replace() 并完成它。
这可以通过正则表达式中的“( )”来完成。快速谷歌搜索“正则表达式子模式”导致 此。
It's probably best to strengthen your regular expression to find a subpattern within the original pattern. That way you can just call preg_replace() and be done with it.
This can be done with "( )" within the regular expression. A quick google search for "regular expression subpatterns" resulted in this.
我不确定我是否理解你的问题。您能否发布一个示例:
如果您只想读取
file.ext,替换正则表达式匹配,并将结果存储在
new_file.ext
中,您所需要的只是:I'm not sure I understand your problem. Could you perhaps post an example of:
If you just want to read
file.ext
, replace a regex match, and store the result innew_file.ext
, all your need is: