繁体   English   中英

PHP正则表达式/搜索并替换多个文件中的多行字符串

[英]PHP regex/search and replace multiline strings in multiple files

我需要.markdown数百个.markdown文件并替换以下多行字符串:

---
---

我目前有以下代码:

foreach (glob("*.markdown") as $filename)
{
    $file = file_get_contents($filename);
    file_put_contents($filename, preg_replace("/regexhere/","replacement",$file));
}

我的问题是,我需要删除每个文件中的多行字符串。

谢谢

可以使用str_replace()更快地完成此操作,如下所示:

<?php
echo "<pre>";

$file="my file
is
this
---
---
goats";

echo str_replace("---\r\n---\r\n",'',$file);

返回:

my file
is
this
goats

现场演示: http : //codepad.viper-7.com/p1Bant

换行符可以是\\n\\r\\n具体取决于操作系统\\软件

如果您真的想使用正则表达式来执行此操作,则应尝试以下操作:

echo "<pre>";

$file="my file
is---dfdf
this---
---
---
goats";

$res = preg_replace("/^---\r\n/m", "", $file);
// m at the end of line will match multiple line so even if you have --- on more than 2 lines it will work
echo $res;

输出将是:

my file
is---dfdf
this---
goats

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM