Joey Pablo Joey Pablo - 1 month ago 23
Twig Question

Make a preg replace on string in twig

I'm trying to find ou a way to make this in twig but I can't find a solution..

preg_replace('/(\w+)([A-Z])/U', '\\1 \\2', ucfirst("thisIsAnExample")) ;


The output in php is "This Is An Example"

Is it possible to do the same thing in twig ?

Egg Egg
Answer

You will need to use a twig extension which will create a custom function for you to use in twig.

For example:

/**
 * Convert camel case to a capitalised human readable string.
 *
 * @param $camelCase string
 * @return string
 */
public function camelCaseToString($camelCase)
{
    return preg_replace("/([A-Z])/", " $1", ucfirst($camelCase));
}

This should convert thisIsAnExample to This Is An Example.

Comments