Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jeroenvanrensen's avatar

PHP preg_replace() - Unknown modifier

Hi everyone,

I have this string:

<h1>Title</h1>
<p>Body Text.</p>

And I want to get rid of the <h1> tag.

I created this RegEx:

<h1>(.+)</h1>

But this does not work:

preg_replace('<h1>(.+)</h1>', '', $string)

I get this error:

ErrorException: preg_replace(): Unknown modifier '('

What's happening here?

Thank you! Jeroen

0 likes
6 replies
bugsysha's avatar

You do not need regex for that

$string = '<h1>Title</h1>';
echo str_replace(['<h1>', '</h1>'], '', $string);
bugsysha's avatar

Your regex mislead me. Then there is no need for ( and ).

preg_replace('/<h1>.+</h1>/', '', $string);
MichalOravec's avatar

This should work

preg_replace('/<h1>(.+)<\/h1>/gm', '', $string)
jeroenvanrensen's avatar

@michaloravec I get this error:

Unknown modifier 'g'

This is my code:

protected function parseMarkdown(string $markdown)
{
    $converter = new CommonMarkConverter(); // the markdown parser class

    $html = $converter->convertToHtml($markdown);

    $html = preg_replace('/<h1>(.+)<\/h1>/gm', '', $html);

    $this->html = $html; // $this->html is a public property
}
MichalOravec's avatar
Level 75

So remove it

preg_replace('/<h1>(.+)<\/h1>/', '', $string)

Please or to participate in this conversation.