1

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

10
  • Two calls to preg_replace()? Commented May 23, 2014 at 1:59
  • @KristerAndersson Sorry I meant the regex to remove the multiline --- strings. I need to match and remove only the multiline --- because elsewhere in the file I have single --- which I need to keep Commented May 23, 2014 at 2:01
  • Sidenote: You may need to remove the http://localhost/ in foreach (glob("http://localhost/*.markdown") Commented May 23, 2014 at 2:04
  • @Fred-ii- why is that? Could you please explain? Commented May 23, 2014 at 2:08
  • because you don't want to access the files via a web-server Commented May 23, 2014 at 2:09

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Plus a demo; bonus. ;-)
2

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

1 Comment

@user2028856 try this if you want to use regex search replace

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.