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

时间:2014-05-23 01:57:11

标签: php regex

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

---
---

我目前有以下代码:

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

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

由于

2 个答案:

答案 0 :(得分:2)

这可以通过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,具体取决于os \ software

答案 1 :(得分:2)

如果你真的想使用正则表达式,那么你应该尝试这个::

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
相关问题