Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php preg_更换preg_内部匹配所有问题_Php_Preg Replace_Preg Match All - Fatal编程技术网

Php preg_更换preg_内部匹配所有问题

Php preg_更换preg_内部匹配所有问题,php,preg-replace,preg-match-all,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 da

我试图在我的数据文件中找到一些特定的块,并替换其中的某些部分。之后,将整个内容(替换数据)放入一个新文件中。目前我的代码如下所示:

$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?);
现在的问题是我不知道如何归还整件东西。基本上,file.ext和new_file.ext除了替换的数据外几乎相同。 有什么建议可以代替
返回整个东西


谢谢大家!

您甚至不需要更换preg_;因为您已经找到了匹配项,所以可以使用普通str_替换,如下所示:

$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);

我不确定我是否理解你的问题。您是否可以发布以下示例:

  • 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);

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

$new_file_contents = preg_replace('/regular(Exp)/', 'replacement', $content);
这可以通过正则表达式中的“()”来完成。在谷歌上快速搜索“正则表达式子模式”,结果是