简体   繁体   中英

PHP regex/search and replace multiline strings in multiple files

I have several hundred .markdown files that I need to loop through and replace the following multiline strings:

---
---

I currently have the following code:

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

My question is, which regex do I need to remove the multi line strings in every file.

Thanks

this can be done faster with str_replace() , like so:

<?php
echo "<pre>";

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

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

which returns:

my file
is
this
goats

Live Demo: http://codepad.viper-7.com/p1Bant

line breaks can be \\n or \\r\\n depending on os\\software

If you really want to do it using Regular expression then you should try this::

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;

Output will be::

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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