How can I delete white spaces of a text in Twig?

How can I delete white spaces of a text in Twig?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Removing Whitespace in Twig: Spaceless vs. String Manipulation

When working with text processing in Twig, specifically within a Symfony application, developers often encounter the need to strip whitespace characters entirely from a string. The goal might be simple: transforming <code>I play</code> into <code>Iplay</code>. While this seems straightforward, the available tools depend heavily on whether you are targeting HTML rendering or raw string manipulation.

The most common misconception is that standard trimming functions will achieve this. Twig provides the trim filter, which removes leading and trailing whitespace but leaves internal spaces intact. Similarly, the built-in PHP trim() function behaves identically. If your input is "I play", using {% set text = 'I play'|trim %} yields "I play", not "Iplay". To remove internal spaces, you must explicitly target them as characters within the string logic.

However, there is a specialized tag designed specifically for this scenario: the spaceless tag. This construct is highly effective when dealing with HTML blocks where whitespace between tags or attributes needs to be removed before rendering. It essentially outputs the content without any whitespace characters.

{% spaceless %}
    <div class="container">
        <p>Some text here</p>
    </div>
{% endspaceless %}
<div class="result">{{ output }}</div>

In this context, spaceless strips the newlines and spaces surrounding tags. However, it operates on HTML structure. If you simply pass a plain string like "I play" into {% spaceless %}{{ text }}{% endspaceless %}, Twig will still render the spaces between the words because they are not considered "whitespace around tags" in the traditional sense; they are content characters. The spaceless tag is primarily intended to collapse whitespace between HTML tags, not to delete all spaces within a text node itself.

Therefore, for raw text manipulation where you want to join every character with no separation, you should use string filters. The most direct approach uses the replace filter to swap space characters with nothingness.

{% set cleanText = 'I play'|replace({ ' ' : '' }) %}
{{ cleanText }} {# Outputs: Iplay #}

This method is robust and predictable. It targets the standard space character (ASCII 32). If your input contains tabs or newlines, you might need to extend the replacement set:

{% set cleanText = 'I play\n' | replace({ ' ' : '', '\n' : '', '\t' : '' }) %}

Using regular expressions via the replace filter is also an option for more complex patterns. You can match any sequence of whitespace characters and replace them with an empty string:

{% set cleanText = 'I play' | replace({ '/\s+/u' : '' }) %}

While powerful, regex replacement requires careful attention to syntax. In Twig, the pattern is passed as a string within the filter. Ensure you handle the delimiters correctly to avoid escaping issues.

Trade-offs and Considerations

Choosing between spaceless and replace depends entirely on your output context. If you are generating an HTML snippet where the goal is to minimize file size or remove formatting artifacts around tags, spaceless is the semantic choice. It prevents the browser from treating whitespace as line breaks in the DOM.

Conversely, if you are processing a string variable for further logic, such as concatenating IDs or creating a hash key, replace is superior. Attempting to use spaceless on a plain text string often yields unexpected results because it does not treat internal word separators as whitespace to be removed; it only collapses whitespace around tags.

Additionally, consider the performance impact. For massive strings processed in a loop, regex replacement might carry a slight overhead compared to simple character substitution, though modern engines handle this efficiently. Always verify that your source text encoding is consistent, as replacing spaces without handling other Unicode whitespace characters (like non-breaking spaces) can lead to subtle bugs where "visual" spaces remain despite the operation.

If you are looking for more advanced string manipulation patterns or need to integrate these logic snippets into larger Laravel projects, resources like LaravelCompany often provide community-driven examples on handling text processing within the framework ecosystem.

Our network