Home » Php » php – Twig split a string after first specific character as delimiter

php – Twig split a string after first specific character as delimiter

Posted by: admin July 12, 2020 Leave a comment


I have a question with the same scenario as this question, except that it might happen that more than one _ is in the text.

An example;


How can I omit everything up until the first underscore (including the underscore) to keep the rest like Filename_whatever.pdf

The random uniquifier can be of a different length, but there will always be an underscore between it and the actual filename.

Like in the mentioned question; {{ filename|split('_')[1] }} might work, but what if the actual filename has an underscore?

I want it preferably in twig just for displaying purposes because the complete unique name is used on different parts of the project as well.

How to&Answers:

As seen in the documentation, split also supports the limit parameter as explode, so you can do :

{{ '57b42a0557cdd_Filename_whatever.pdf'  | split('_', 2)[1] }}
{{ '57b42a0557cdd_Filename_what_ever.pdf' | split('_', 2)[1] }}
{{ '57b42a0557cdd_File_name_whatever.pdf' | split('_', 2)[1] }}


Another option (assuming that the file is part of an entity) is to write a function on the entity that that returns what you want.
For example;


namespace AppBundle\Entity;

class MyEntity
    // ... other attributes

    private $hashFileName;

    private $cleanFileName;

    // other functions

    public function getHashFileName()
        // as per you example; 57b42a0557cdd_Filename_whatever.pdf
        return $this->hashFileName;

    public function getCleanFileName()
        $withouthash = explode('_', $this->hashFileName,2);
        return $withouthash[1];

Then in your twig file;

{{ myObject.cleanfilename }}