Twig - get the number of words from a string

twig count loop
twig truncate
twig array length
pact word count
twig count php
timber twig length
twig variable size
twig php length

I am using craft cms, that uses twig templating, and would like to get the number of words from the string. I have tried with using the PHP function str_word_count() :

       {% for entry in entries %}
          <a href="{{ entry.url }}">
            <div class="media-object">
              <div class="small-4 columns">
                <div class="media-object-section">
                  <img src= "{{ entry.topImage.first().getUrl('square') }}">
                </div>
              </div>
              <div class="small-8 columns">
                <div class="media-object-section main-section">
                  <h4>{{ entry.title }}</h4>
                  {% set numberOfWords = str_word_count(entry.summary) %}
                  <p>{{ entry.summary |split(" ")|slice(0, 15)|join(" ") }}</p>
                  <p>{{ entry.dateUpdated | date('j. F Y') }}</p>
                </div>
              </div>
            </div>
          </a>
        {% endfor %}

But, I got an error:

Unknown "str_word_count" function.

How can I get the number of words from the string in the twig template?

You can do it this way:

{% set numberOfWords = entry.summary|split(' ')|length %}

Split function will split your string to array by given parameter (space in this case) and length will count array elements.

How to check how many characters there are in my string?, Twig has a length filter that can help you with that: {% set stringLength If you are attempting to get a count of the string, you can use Twigs dump function. The length filter returns the number of items of a sequence or mapping, or the length of a string. For objects that implement the Countable interface, length will use the return value of the count() method. For objects that implement the __toString() magic method (and not Countable), it will return the length of the string provided by that method.

Make a custom extension and make use of any PHP functions inside: https://symfony.com/doc/current/templating/twig_extension.html

split - Documentation - Twig, split ¶. The split filter splits a string by the given delimiter and returns a list of strings:  If the delimiter is an empty string, then value will be split by equal chunks. Length is set by the limit argument (one character by default). Internally, Twig uses the PHP explode or str_split (if delimiter is empty) functions for string splitting.

Well, as suggested by Tomas, I wrote my own twig (filter) function for this case:

    <?php

namespace AppBundle\TwigExtensions;


use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Twig\TwigFilter;

class TwigExtensions extends \Twig_Extension
{

    /**
     * this is needed
     *
     * @return string
     */
    public function getName()
    {
        return 'your_twig_extensions';
    }

    /**
     * 
     * @return array
     */
    public function getFunctions()
    {
        return array();
    }

    /**
     * 
     *
     * @return array
     */
    public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('strWordCount', array($this, 'strWordCount')),
        );
    }


  /**
     * count Words in string
     *
     * @return string
     */
    public function strWordCount($text = null)
    {
        return str_word_count($text);
    }

}

title - Documentation - Twig, title ¶. The title filter returns a titlecased version of the value. Words will start with uppercase letters, all remaining characters are lowercase:  Twig - The flexible, fast, and secure template engine for PHP slice - Documentation - Twig - The flexible, fast, and secure PHP template engine About

length - Documentation - Twig, The length filter returns the number of items of a sequence or mapping, or the the Countable interface, length will use the return value of the count() method. (​and not Countable ), it will return the length of the string provided by that method. You can control the number of decimal places, decimal point, and thousands separator using the additional arguments: 1 {{ 9800.333 | number_format ( 2 , '.' , ',' ) }}

slice - Documentation - Twig, The slice filter extracts a slice of a sequence, a mapping, or a string: If length is given and is positive, then the sequence will have up to that many elements in it  A protip by preclowski about php, symfony, and twig. Sponsored by #native_company# — Learn More

Truncating text with Twig macros in Craft CMS, The first macro truncates text by number of words and second by number of from the text before truncating to avoid getting wrong characters count. text - string to truncate. length - desired length of truncated text - in a  Twig - The flexible, fast, and secure template engine for PHP trim - Documentation - Twig - The flexible, fast, and secure PHP template engine About

Comments
  • whats your php version?
  • what if you have two part words ?
  • Then my answer would count it as single. For example "foo-bar" would result in 1 word. But even str_word_count by definition would count it as 1: "For the purpose of this function, 'word' is defined as a locale dependent string containing alphabetic characters, which also may contain, but not start with "'" and "-" characters."
  • i was thinking more about two parts words without "-", like "ping pong" for exemple