简体   繁体   English

如何在字符串末尾添加空格?

[英]How to add a space to the end of a string?

I searched online and found the str_pad() function but this is not what I need. 我在线搜索并找到了str_pad()函数,但这不是我所需要的。 I need to automatically add a space at the end of a string. 我需要在字符串的末尾自动添加一个空格。

The string value returned can be my default value or a custom value supplied by an extending developer. 返回的字符串值可以是我的默认值,也可以是扩展开发人员提供的自定义值。 If the developer supplies extra characters, which they can, then the str_pad() approach won't always work. 如果开发人员提供了多余的字符,那么str_pad()方法将永远无法工作。

Is there a simple function for this to ALWAYS add one space to the end of a string? 是否有一个简单的函数始终将一个空格添加到字符串的末尾? Like a trim() but works the opposite? trim()但效果相反?

Here is what I am doing. 这是我在做什么。

str_pad($this->filter('custom_hook_name', FALSE, 'column span-12'), 15);

My default is 'column span-12' 我的默认设置是'column span-12'

However the developer might return their custom classes as well so the return string value could look something like... 但是,开发人员也可能返回其自定义类,因此返回字符串值可能类似于...

'dev-brand-column span-12'

'dev-brand-col col-12'

// etc...

I need to add a space as the end of the string regardless of the string length. 无论字符串的长度如何,我都需要在字符串的末尾添加一个空格。

How can I achieve that? 我该如何实现? I find nothing that works the opposite of trim() like. 我找不到与trim()相反的东西。

使用rtrim首先删除可能存在的字符串末尾的所有空格,然后自己添加一个空格:

$str = rtrim($str) . " ";

I think that sprintf() can help you... 我认为sprintf()可以帮助您...

For example : 例如 :

$string = "Bond";
printf("%-10s",    $string);

Will return : 将返回 :

Bond

With 6 spaces at the end of the string. 字符串末尾有6个空格。

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM