Returns the longest common prefix between two strings with respect to a given delimiter. It can either return the match including the trailing delimiter or, if desired, only the match up to but not including the last full delimiter-separated segment. Useful for dimming the shared path prefix when rendering hierarchical keys or dot-separated field names in tables.
Syntax
hublify.commonPrefix(string $a, string $b, string $delimiter, bool $includeDelimiter = true): ?string
- $a – string
The first value to compare. - $b – string
The second value to compare. - $delimiter – string
The substring that separates segments (e.g.,".","/",":"). - $includeDelimiter – bool (default:
true)
Iftrue, the match is returned including the trailing delimiter (e.g.,"order.delivery.").
Iffalse, the match is returned without the trailing delimiter (e.g.,"order.delivery"). Also counts as a match when one string ends and the other continues exactly at the next delimiter boundary (e.g.,"order"vs"order.delivery").
Returns: the matched prefix as string, or null if there is no valid match.
Behavior
- Matches are computed on the longest common prefix and then trimmed to the last full delimiter boundary.
- With
$includeDelimiter = true, at least one delimiter must appear within the matched prefix; otherwise result isnull. - With
$includeDelimiter = false, a match can be the whole shorter string if the longer string continues exactly at a delimiter (e.g.,"order"&"order.delivery"⇒"order").
Examples
{% set a = 'order.delivery.firstname' %}
{% set b = 'order.delivery.lastname' %}
{{ hublify.commonPrefix(a, b, ".", true) }} => "order.delivery."
{{ hublify.commonPrefix(a, b, ".", false) }} => "order.delivery"{% set a = 'order' %}
{% set b = 'order.delivery' %}
{{ hublify.commonPrefix(a, b, ".", true) }} => null
{{ hublify.commonPrefix(a, b, ".", false) }} => "order"{% set a = 'customer.addr.city' %}
{% set b = 'customer.addr.zip' %}
{{ hublify.commonPrefix(a, b, ".", true) }} => "customer.addr."
{{ hublify.commonPrefix(a, b, ".", false) }} => "customer.addr"{% set a = 'env:prod:eu' %}
{% set b = 'env:prod:us' %}
{{ hublify.commonPrefix(a, b, ":", true) }} => "env:prod:"
{{ hublify.commonPrefix(a, b, ":", false) }} => "env:prod"Typical Twig usage: gray-out the shared prefix
Dim the common prefix (segment-wise) and show the remainder normally:
{% set value = 'order.delivery.firstname' %}
{% set previous = 'order.delivery.lastname' %}
{% set prefix = hublify.commonPrefix(value, previous, ".", true) %}
{% if prefix is not null %}
<span style="color:#999;">{{ prefix }}</span>{{ value|slice(prefix|length) }}
{% else %}
{{ value }}
{% endif %}