user2028856
user2028856

Reputation: 3183

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

Upvotes: 1

Views: 1088

Answers (2)

D555
D555

Reputation: 1840

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

Upvotes: 2

user557846
user557846

Reputation:

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

Upvotes: 2

Related Questions