【问题标题】:Twig split a string after first specific character as delimiterTwig 在第一个特定字符后拆分字符串作为分隔符
【发布时间】:2016-08-17 09:35:25
【问题描述】:

我有一个问题与this question 的情况相同,但文本中可能会出现多个_

一个例子;

57b42a0557cdd_Filename_whatever.pdf

我怎样才能省略直到第一个下划线(包括下划线)的所有内容,以保留其余部分,如 Filename_whatever.pdf

随机唯一符可以有不同的长度,但在它和实际文件名之间总会有一个下划线。

就像在提到的问题中一样; {{ filename|split('_')[1] }} 可能有效,但如果实际文件名有下划线怎么办?

我希望它最好在 twig 中仅用于显示目的,因为完整的唯一名称也用于项目的不同部分。

【问题讨论】:

    标签: php symfony twig


    【解决方案1】:

    documentation中所见,split也支持limit参数为explode,所以你可以do

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

    【讨论】:

    • 太棒了!不知怎的,我一开始不明白那个。但是现在我看到 2 作为限制参数发生了什么。谢谢
    【解决方案2】:

    另一种选择(假设文件是​​实体的一部分)是在实体上编写一个返回所需内容的函数。
    例如;

    <?php
    
    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];
        }
    }
    

    然后在你的树枝文件中;

    {{ myObject.cleanfilename }}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-23
      • 2017-04-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-29
      • 1970-01-01
      相关资源
      最近更新 更多