2

How can i replace unused section in content. For example:

$content = "
    Test content

    [section]
        Section Content
    [section]

    End.
";

$content = preg_replace('/\[section\](.*)\[section\]/', '', $content);

Thanks

adoweb
  • 47
  • 5
  • add the `s` modifier to match newlines with `.`. Also don't forget to make your expression [ungreedy](http://stackoverflow.com/questions/3075130/difference-between-and-for-regex) `/\[section\](.*?)\[section\]/s` – HamZa Nov 23 '13 at 22:10

2 Answers2

3

The s modifier allows a dot metacharacter in the pattern to match all characters, including newlines.

The i modifier is used for case-insensitive matching allowing both upper and lower case letters. By adding the quantifier ? it makes for a non greedy match and matches the least amount possible.

$content = preg_replace('/\[section\].*?\[section\]/si', '', $content);

See Demo

hwnd
  • 69,796
  • 4
  • 95
  • 132
2

What's the regex for? This should work and will run a lot quicker:

$content = explode('[section]',$content);
$content = $content[0].$content[2];
cronoklee
  • 6,482
  • 9
  • 52
  • 80