3

I have a string from a multi-line plain text field and I'd like to trim any trailing spaces before new lines.

With plain regex I would use this expression: /\s*$/gm

Using

{{ string|replace('/\\s*$/', '') }}

will trim out the last trailing space of the string (same as the trim filter would), but not before every new line.

I have tried

{{ string|replace('/\\s*$/gm', '') }}

and

{{ string|replace('/\\s*$/m', '') }}

but that doesn't have any effect.

How can I apply the m modifier to the replace filter?

4

Currently it’s not possible to pass regex modifiers to the |replace filter. You’d have to just do this manually:

{% set str = "foo     \nbar    " %}
{% set trimmed = "" %}

{% for line in str|split("\n") %}
    {% set trimmed = trimmed ~ (trimmed ? "\n") ~ line|replace('/\\s*$/', '') %}
{% endfor %}

UPDATE

As of Craft 2.5, the |replace filter supports regex modifiers.

| improve this answer | |
1

Just needed something similar today, and patched in a new replace filter to the RetconHTML plugin. The filter – called retconReplace – uses preg_replace and might be able to help you out:

{{ string|retconReplace('/\s*$/m') }}

You'll find the wiki on retconReplace here.

| improve this answer | |
  • 1
    That’s awesome, thanks Mats. And your plugin has come in very handy on another site I've been working on :) – Katrin Oct 16 '15 at 15:25
0

Would the spaceless filter work wrapped in div?

| improve this answer | |
  • 2
    If you run the field value through |spaceless (with or without a div), it will only remove the whitespace at the outer edges of the text; not all of the trailing whitespace on each line of the text. – Brandon Kelly Sep 24 '15 at 14:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.