preg_replace GitHub flavored markdown codeblock and remove

165 views Asked by At

I'm attempting to capture all occurrences of GitHub flavored Markdown code blocks and then remove them from the end result of my application. I have a matching RegEx pattern which can be seen here: http://www.regexpal.com/?fam=96555, however when I run it in the preg_replace function it fails to remove the code block.

Here's the preg_replace function I'm running:

preg_replace("/(```[a-z]*\n[\s\S]*?\n```)/", "", $content);

Here's the original content I'm running it against, which returns unchanged when running it through the above function:

```php
<?php echo 'test'; ?>
```
Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia 
Curae; Donec velit neque, auctor sit amet aliquam vel, ullamcorper sit amet ligula. 
Donec rutrum congue leo eget malesuada. Curabitur non nulla sit amet nisl 
tempus convallis quis ac lectus. Donec sollicitudin molestie malesuada. Nulla 
porttitor accumsan tincidunt. Curabitur aliquet quam id dui posuere blandit.

The end result should be:

Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia 
Curae; Donec velit neque, auctor sit amet aliquam vel, ullamcorper sit amet ligula. 
Donec rutrum congue leo eget malesuada. Curabitur non nulla sit amet nisl 
tempus convallis quis ac lectus. Donec sollicitudin molestie malesuada. Nulla 
porttitor accumsan tincidunt. Curabitur aliquet quam id dui posuere blandit.

Any help would be appreciated. Thank you!

1

There are 1 answers

1
bobble bubble On BEST ANSWER

Have a try with \R which is an escape for any linebreak sequence instead of \n.

preg_replace('/```[a-z]*\R.*?\R```/s', "", $content);
  • Maybe you have an \r between [a-z] and \n
  • To check replace [a-z]*\n by [a-z]*\r?\n
  • Further used .*? with dot match all flag s

Here is a demo at eval.in

Also be aware that your pattern indeed looks like this when using double quotes (not the issue).