<p>I'm on my phone, so I'm not able to test, but it looks to me like your regex is explicitly expecting the string you're testing to start with <code>&lt;ul&gt;</code> and end with <code>&lt;/ul&gt;</code>, and despite the multiline flag, any line breaks at the start or end of the string will prevent a match.</p>
<p>Try removing the <code>^</code> and <code>$</code> from the start and end your pattern match to disable explicit start and end of string matching.</p>

CC BY-SA 4.0
2022-09-27T23:27:13.127Z
2022-09-28T00:05:22.283Z
2022-09-28T00:05:22.283Z
stevecomrie
<p>I understand that for a long time the <code>|replace</code> filter has <a href="https://craftcms.stackexchange.com/a/11618/3507">supported regex modifiers</a>, but I can't seem to get the syntax right for multiline searches.</p>
<p>For example, here I want to extract the internal markup within a list that's been generated via Markdown, so I can do something with the internals:</p>
<pre><code>{% set html = html|replace('/\\n/', '')|replace('/^(&lt;ul&gt;)(.*)(&lt;\\/ul&gt;)$/', '$2') %}
</code></pre>
<p>That works, but I should be able to use a modifier with the second replace so I don't have to use the first one, right?</p>
<p>But none of these work:</p>
<pre><code>{% set html = html|replace('/^(&lt;ul&gt;)(.*)(&lt;\\/ul&gt;)$/m', '$2') %}

{% set html = html|replace('/^(&lt;ul&gt;)(.*)(&lt;\\/ul&gt;)$/\\m', '$2') %}

{% set html = html|replace('/^(&lt;ul&gt;)(.*)(&lt;\\/ul&gt;)$/(?m)', '$2') %}
</code></pre>
<p>What am I doing wrong?</p>

<regex><replace>
Best way to do a multi-line regex replace?
# Best way to do a multi-line regex replace?

(Asked by: username_0 on 2022-09-27)

I understand that for a long time the |replace filter has supported regex modifiers, but I can't seem to get the syntax right for multiline searches.
For example, here I want to extract the internal markup within a list that's been generated via Markdown, so I can do something with the internals:
{% set html = html|replace('/\\n/', '')|replace('/^()(.*)(<\\/ul>)$/', '$2') %}

That works, but I should be able to use a modifier with the second replace so I don't have to use the first one, right?
But none of these work:
{% set html = html|replace('/^()(.*)(<\\/ul>)$/m', '$2') %}

{% set html = html|replace('/^()(.*)(<\\/ul>)$/\\m', '$2') %}

{% set html = html|replace('/^()(.*)(<\\/ul>)$/(?m)', '$2') %}

What am I doing wrong?

**Tags:** regex, replace

---

## 1 answers

### Answer by username_1 on 2022-09-27. Score: 1

I'm on my phone, so I'm not able to test, but it looks to me like your regex is explicitly expecting the string you're testing to start with  and end with , and despite the multiline flag, any line breaks at the start or end of the string will prevent a match.

Try removing the `^` and `$` from the start and end your pattern match to disable explicit start and end of string matching.


---

