Twig在第一个特殊字符作为分隔符后分割一个字符串(Twig split a string after first specific character as delimiter)

编程入门 行业动态 更新时间:2024-10-23 06:32:50
Twig在第一个特殊字符作为分隔符后分割一个字符串(Twig split a string after first specific character as delimiter)

我对这个问题的相同场景有一个疑问,除了文本中可能会出现多个_ 。

一个例子;

57b42a0557cdd_Filename_whatever.pdf

我怎么能省略所有内容,直到第一个下划线(包括下划线)来保持其余的像Filename_whatever.pdf

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

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

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

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;

57b42a0557cdd_Filename_whatever.pdf

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.

最满意答案

从文档中可以看出, split还支持limit参数为explode ,因此您可以这样做 :

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

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] }}

更多推荐

本文发布于:2023-08-07 04:11:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1461228.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:第一个   字符串   特殊字符   分隔符   Twig

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!