How to delete white spaces of a text in twig?

You can also create your own filter to do that

Example :

class MyExtensions extends \Twig_Extension
{
    public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('removeWhiteSpace', array($this, 'removeWhiteSpace'), array('is_safe' => array('html'))),
        );
    }

    public function removeWhiteSpace($string)
    {

       return preg_replace('/\s+/', '', $string);
    }
}

Declare it as service :

myextensions.twig_extension:
      class: YourProject\YourBundle\Twig\MyExtensions
      public: false
      tags:
          - { name: twig.extension }

And call it in yours twig template :

{{ "Test remove white space"|removeWhiteSpace }}

First let's see what you tried and why that wasn't working:

  • Spaceless: is not working because "Use the spaceless tag to remove whitespace between HTML tags, not whitespace within HTML tags or whitespace in plain text" see spaceless documentation.
  • Trim: is not working because "The trim filter strips whitespace (or other characters) from the beginning and end of a string" see trim documentation.

What you need to use is the following:

{{ 'Some Text With Spaces'|replace({' ': ''}) }}

This will output:

SomeTextWithSpaces

More details in the documentation.


For me this was not working when string contains non-breaking whitespaces:

stringWithNonBreakingWhitespace|replace({' ':''}

To replace non-braking whitespace you have to use escape sequence:

stringWithNonBreakingWhitespace|replace({'\xc2\xa0':''}

Try this:

{{ "I plays"|replace({' ':''}) }}

Tags:

Php

Twig

Symfony