Find substring in the string in TWIG

Find substring in the string in TWIG

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

Stefan Bogdanescu

Founder & Senior Architect

Finding Substrings in Twig Without Native Functions

Developers migrating from PHP to Twig often hit a wall when trying to replicate specific string manipulation functions like strstr or strpos. In PHP, these are built-in and available at the global scope. However, Twig is designed with a philosophy of safety and minimalism; it does not expose every PHP function by default to prevent accidental execution of dangerous code or unintended side effects. Attempting to call a non-existent function like twig_strpos will result in a template error, leaving you wondering if the functionality simply isn't there.

The solution involves extending Twig's functionality without altering the core engine or compromising its security model. You can achieve this by creating a custom extension that registers your own functions. This approach is lightweight, requires no changes to your main application logic, and keeps your templates clean.

Implementing a Custom Extension

To add string search capabilities to your Twig environment, you need to create a class that extends Twig_Extension (in legacy versions) or implements the Twig\Extension\AbstractExtension interface (in Twig 1.x and later). The modern approach using AbstractExtension is preferred for new projects.

Here is how you define a custom extension in PHP:

<?php

use Twig\Environment;
use Twig\Loader\FilesystemLoader;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

class StringSearchExtension extends AbstractExtension
{
    public function getFunctions()
    {
        return [
            new TwigFunction('strpos', [$this, 'strpos']),
            new TwigFunction('strstr', [$this, 'strstr']),
            new TwigFunction('substr', [$this, 'substr']),
        ];
    }

    public function strpos($haystack, $needle)
    {
        return strpos($haystack, $needle);
    }

    public function strstr($haystack, $needle)
    {
        return strstr($haystack, $needle);
    }

    public function substr($string, $start, $length = null)
    {
        return substr($string, $start, $length);
    }
}

Registering this extension is straightforward. You add it to your Twig environment instance:

$loader = new FilesystemLoader();
$twig = new Environment($loader);
$twig->addExtension(new StringSearchExtension());

Once registered, you can use these functions directly inside your templates exactly as if they were native Twig features. This pattern is standard practice for bridging the gap between PHP's extensive string library and Twig's restricted scope.

Handling Edge Cases and Return Values

A critical distinction exists between strpos and strstr, a nuance that developers sometimes overlook when porting logic from PHP to templates.

The strpos function returns the numeric position of the first occurrence of the needle as an integer, or false if not found. In Twig, which is dynamically typed but lacks explicit type checking at runtime like strict PHP configurations, you must handle this carefully. If you compare the result directly in a conditional without checking for false, Twig might treat the boolean conversion incorrectly depending on your version and configuration.

{% if string_search|default('') %}
    {# This checks if the substring was found #}
{% endif %}

A more robust pattern is to check explicitly:

{% set position = 'hello world'|strpos('world') %}
{% if position !== false %}
    Found at index {{ position }}
{% else %}
    Substring not found.
{% endif %}

On the other hand, strstr returns the portion of the string from the first occurrence of the needle through to the end of the string, or false if the needle is not found. This allows you to extract substrings conditionally within your templates without writing complex logic.

Performance Considerations

While wrapping PHP functions in a Twig extension adds a negligible overhead compared to native Twig filters, it does add a layer of abstraction. If you find yourself calling these functions hundreds of times per request in high-traffic applications, consider optimizing the rendering logic instead of relying on repeated function calls. However, for most content management systems and dynamic sites, this performance hit is imperceptible.

The real trade-off here is maintainability versus flexibility. By keeping these functions in a dedicated extension file, you centralize your string manipulation logic. If you later decide to replace strstr with a more performant alternative or add regex support, you only need to modify that single class rather than scattering custom filters throughout your project.

For complex string operations involving regular expressions, Twig also supports the regex filter in newer versions, which can sometimes replace the need for custom extensions entirely. However, for direct PHP function mirroring like strstr, a custom extension remains the most reliable and explicit solution.

Our network